/*******************************************************************************
Project : Bank Expansion and Moneylender Interest Rates - RDD Evidence from India
Authors : Briones L., Chiseliov V., Gushchin E., Guttensen J.
File    : All Tables.do
Purpose : Master script to generate all tables in the replication package.
*******************************************************************************/

clear all
set more off

*==============================================================================
* SETUP
*==============================================================================

* Optional installs (run once)
* ssc install rdrobust
* ssc install shapley2

cd "`c(pwd)'\Data"

*==============================================================================
* TABLE RUN TOGGLES (1 = run, 0 = skip)
*==============================================================================

local table_01 1	// Descriptive Statistics	// Table 1
local table_02 1	// Smoothness (2003) 		// Table 2
local table_03 1	// Main regressions			// Table 3
local table_04 1	// Wealth					// Table 4
local table_05 1	// Loan amount				// Table 5
local table_06 1	// Take-up					// Table 6
local table_07 1	// All controls				// Table 7
local table_C1 1	// Bank branch expansion	// Table C1
local table_C2 1	// Smoothness (NSS 70)		// Table C2
local table_C3 1	// Placebo cutoffs			// Table C3
local table_C4 1	// Polynomials				// Table C4
local table_C5 1	// Bandwidths				// Table C5
local table_C6 1	// Term loans - 2003		// Table C6
local table_C7 1	// Term loans - 2013		// Table C7


if `table_01'{

eststo clear

*-------------------------------*
* AIDIS 2003
*-------------------------------*
use AllIndiaI, clear
*keep if abs(stdlog_i) < 4
drop if missing(log_i, B_Ratio_Dist_Ex)

* rename interest rate to a common name
rename B15_2_q10 Interest_rate

* CPI merge + inflation-adjusted loan amount
rename B15_2_q3 b14_q3
destring b14_q3, replace
merge m:1 b14_q3 using CPI_index, keepusing(CPI_index)
drop if _merge == 2
drop _merge

gen loan_amount = (B15_2_q5 / CPI_index) * 100
gen Short_term  = inlist(B15_2_q8,"1","2")

eststo a03_full: estpost summarize Interest_rate loan_amount Short_term
eststo a03_ml  : estpost summarize Interest_rate loan_amount Short_term if inlist(B15_2_q6,"10","11")
eststo a03_bk  : estpost summarize Interest_rate loan_amount Short_term if inlist(B15_2_q6,"02","03")

*-------------------------------*
* AIDIS 2013
*-------------------------------*
use AllIndiaII, clear
*keep if abs(stdlog_i) < 4
drop if missing(log_i, B_Ratio_Dist_Ex)

* rename interest rate to the same common name
rename b14_q10 Interest_rate

* CPI merge + inflation-adjusted loan amount
capture drop _merge
merge m:1 b14_q3 using CPI_index, keepusing(CPI_index)
drop if _merge == 2
drop _merge

gen loan_amount = (b14_q5 / CPI_index) * 100
gen Short_term  = inlist(b14_q8,1,2)

eststo a13_full: estpost summarize Interest_rate loan_amount Short_term
eststo a13_ml  : estpost summarize Interest_rate loan_amount Short_term if inlist(b14_q6,13,14)
eststo a13_bk  : estpost summarize Interest_rate loan_amount Short_term if inlist(b14_q6,2,3)

*-------------------------------*
* Export table (means with SDs below; no N row)
* - Cols: Full ML Bank | Full ML Bank
* - Group headers: AIDIS 2003 for first 3, AIDIS 2013 for next 3
* - SD row rounding: row1 fmt(2), row2 fmt(0), row3 fmt(2)
*-------------------------------*
*============================================================*
*  Summary stats table (NO N row, NO (1)(2)(3) numbering,
*  NO extra midrules between blocks, single top/bottom rules)
*============================================================*

local OUT "output/tables/table_01_summary_stats.tex"
capture erase "`OUT'"

*---------------- Header (manual) ----------------*
file open fh using "`OUT'", write replace
file write fh "\begin{tabular}{lcccccc}" _n
file write fh "\toprule" _n
file write fh " & \multicolumn{3}{c}{AIDIS 2003} & \multicolumn{3}{c}{AIDIS 2013} \\" _n
file write fh "\cmidrule(lr){2-4}\cmidrule(lr){5-7}" _n
file write fh " & Full & ML & Bank & Full & ML & Bank \\" _n
file write fh "\midrule" _n
file close fh

*---------------- Body: Interest_rate ----------------*
esttab a03_full a03_ml a03_bk a13_full a13_ml a13_bk ///
using "`OUT'", append fragment ///
nomtitles nonotes nonumber noobs ///
keep(Interest_rate) ///
varlabels(Interest_rate "Interest_rate (\%)") ///
cells("mean(fmt(2))" "sd(par fmt(2))") ///
collabels(none)

*---------------- Body: loan_amount ----------------*
esttab a03_full a03_ml a03_bk a13_full a13_ml a13_bk ///
using "`OUT'", append fragment ///
nomtitles nonotes nonumber noobs ///
keep(loan_amount) ///
varlabels(loan_amount "Loan amount (rupees)") ///
cells("mean(fmt(%12.0fc))" "sd(par fmt(%12.0fc))") ///
collabels(none)

*---------------- Body: Short_term ----------------*
esttab a03_full a03_ml a03_bk a13_full a13_ml a13_bk ///
using "`OUT'", append fragment ///
nomtitles nonotes nonumber noobs ///
keep(Short_term) ///
varlabels(Short_term "Short_term = 1") ///
cells("mean(fmt(2))" "sd(par fmt(2))") ///
collabels(none)

*---------------- Footer (manual) ----------------*
file open fh using "`OUT'", write append
file write fh "\bottomrule" _n
file write fh "\end{tabular}" _n
file close fh



}


if `table_02' {

use AllIndiaII, clear

keep if abs(stdlog_i)<4  /* remove observations beyond 4 standard deviations*/
drop if log_i==.
drop if B_Ratio_Dist_Ex==.

count if inlist(b14_q3, 2010,2011,2012,2013) & inlist(b14_q6,13,14)
count if inlist(b14_q3, 2010,2011,2012,2013)
count if inlist(b14_q6,13,14)

eststo: rdrobust log_i B_Ratio_Dist_Ex if inlist(b14_q3, 2010,2011,2012,2013) & inlist(b14_q6,13,14), p(1) fuzzy(treatment) weights(Weight_SS) vce(cluster NSS_70_Codes) bwselect(mserd) 

/* Store bandwidth and sample statistics */
global h = e(h_l)

/****************************************************/
/* HOUSEHOLD CHARACTERISTICS DATA PREPARATION */
/* Block 4-13: Various household asset and demographic data */
/****************************************************/

/* --------- BLOCK 4: Demographic data --------- */
use "59_round\Visit 1 & 2 Combined_Block 4_demographic and other particulars of household members", clear
keep if B4_q3=="1"  /* Keep only household heads */

/* Create demographic variables */
gen female = (B4_q4=="2")
gen education = (inlist(B4_q7,"01","02","03","04","05")) /* until middle school */
gen age = B4_q5

save "59_round\b4_wavei", replace

/* --------- BLOCK 5: Land ownership --------- */
use "59_round\Visit 1 & 2 Combined_Block 5_land owned by the household as on the date of survey and related transactions", clear

/* Calculate total land value per household */
bysort HHID: egen value_area = total(B5_q11)
duplicates drop HHID, force

save "59_round\b5_wavei", replace

/* --------- BLOCK 7: Livestock and poultry --------- */
use "59_round\Visit 1 & 2 Combined_Block 7_livestock and poultry owned by the household  on the date of survey and related transactions.dta", clear

/* Calculate total poultry value per household */
bysort HHID: egen value_poultry = total(B7_q10)
duplicates drop HHID, force

save "59_round\b7_wavei", replace

/* --------- BLOCK 8: Agricultural machinery --------- */
use "59_round\Visit 1 & 2 Combined_Block 8_agricultural machinery and implement owned by the household as on the date of survey.dta", clear

/* Calculate total agricultural machinery value */
bysort HHID: egen value_agmachinery = total(B8_q10)
duplicates drop HHID, force

save "59_round\b8_wavei", replace

/* --------- BLOCK 9: Non-farm business equipment --------- */
use "59_round\Visit 1 & 2 Combined_Block 9_non-farm business equipment owned by the household as on date of survey and related transactions.dta", clear

/* Calculate total non-farm equipment value */
bysort HHID: egen value_nonfarm = total(B9_q10)
duplicates drop HHID, force

save "59_round\b9_wavei", replace

/* --------- BLOCK 10: Transport equipment --------- */
use "59_round\Visit 1 & 2 Combined_Block 10_transport  equipment owned by  the  household as on the date of  survey and  related tnansactions ", clear

/* Calculate total transport equipment value */
bysort HHID: egen value_tequipment = total(B10_q4)
duplicates drop HHID, force

save "59_round\b10_wavei", replace

/* --------- BLOCK 11: Durable assets --------- */
use "59_round\Visit 1 & 2 Combined_Block 11_durable assets owned by the household as on the date of survey and related transactions.dta", clear

/* Calculate total durable assets value */
bysort HHID: egen value_durable = total(B11_q10)
duplicates drop HHID, force

save "59_round\b11_wavei", replace

/* --------- BLOCK 13: Other financial assets --------- */
use "59_round\Visit 1 & 2 Combined_Block 13_financial assets other than shares & debentures owned by the household.dta", clear

/* Calculate total other financial assets value */
bysort HHID: egen value_otherfin = total(B13_q8)
duplicates drop HHID, force

save "59_round\b13_wavei", replace

/* --------- BLOCK 17: Capital expenditure --------- */
use "59_round\Visit 1 & 2 Combined_Block 17pt1_specified items on which household incurred expenditure.dta", clear

/* Calculate total capital expenditure */
destring B17_1_q3 B17_1_q4, replace
gen cap = B17_1_q3 + B17_1_q4
bysort HHID: egen capital_exp = total(cap)
duplicates drop HHID, force

save "59_round\b17_wavei", replace

/****************************************************/
/* MAIN HOUSEHOLD DATA MERGING */
/****************************************************/

/* --------- Base household data (Block 3) --------- */
use "59_round\Visit 1 & 2 Combined_Block 3_Household characteristics.dta", clear 

/* Create district code and merge mapping data */
gen NSS_59_Codes = State + District
merge m:1 NSS_59_Codes using "MOF_Census_NSS_59.dta"
drop if _merge != 3
drop _merge


/* --------- Merge all household characteristic data --------- */

/* Merge demographic data (Block 4) */
merge m:1 HHID using "59_round\b4_wavei.dta", keepusing(age education female) force
drop _merge

/* Merge land value data (Block 5) */
merge m:1 HHID using "59_round\b5_wavei.dta", keepusing(value_area)
replace value_area = 0 if _merge == 1
drop _merge

/* Merge poultry value data (Block 7) */
merge m:1 HHID using "59_round\b7_wavei.dta", keepusing(value_poultry)
replace value_poultry = 0 if _merge == 1
drop _merge

/* Merge agricultural machinery value data (Block 8) */
merge m:1 HHID using "59_round\b8_wavei.dta", keepusing(value_agmachinery)
replace value_agmachinery = 0 if _merge == 1
drop _merge

/* Merge non-farm equipment value data (Block 9) */
merge m:1 HHID using "59_round\b9_wavei.dta", keepusing(value_nonfarm)
replace value_nonfarm = 0 if _merge == 1
drop _merge

/* Merge transport equipment value data (Block 10) */
merge m:1 HHID using "59_round\b10_wavei.dta", keepusing(value_tequipment)
replace value_tequipment = 0 if _merge == 1
drop _merge

/* Merge durable assets value data (Block 11) */
merge m:1 HHID using "59_round\b11_wavei.dta", keepusing(value_durable)
replace value_durable = 0 if _merge == 1
drop _merge

/* Merge other financial assets value data (Block 13) */
merge m:1 HHID using "59_round\b13_wavei.dta", keepusing(value_otherfin)
replace value_otherfin = 0 if _merge == 1
drop _merge

/* Merge capital expenditure data (Block 17) */
merge m:1 HHID using "59_round\b17_wavei.dta", keepusing(capital_exp)
replace capital_exp = 0 if _merge == 1
drop _merge

/****************************************************/
/* DATA CLEANING AND VARIABLE CREATION */
/****************************************************/

/* Convert string variables to numeric */
destring B3_q5 B3_q6 B3_q9, replace
destring NSS_59_Codes, replace
destring State, replace

/* Create log transformations for selected variables */
local vars "B3_q8 B3_q13"
foreach i of local vars {
gen log_`i' = log(`i')
summarize log_`i'
generate stdlog_`i' = (log_`i' - r(mean))/r(sd)
}

/* Create state dummy variables */
forvalues i = 1/36 {
gen state`i' = (State == `i')
}

/* Define fixed effects */
global fixeffects state3 state6 state8 state9 state10 state11 state12 state14 state17 state18 state19 state20 state21 state23 state24 state27 state28 state29 state32 state33 

/* Create demographic and socioeconomic variables */
gen minority_religion = (B3_q5 == 2 | B3_q5 == 3 | B3_q5 == 7 | B3_q5 == 9)
gen minority_social = (B3_q6 == 1 | B3_q6 == 2)
gen kisan = (B3_q9 == 1)
gen above = (B_Ratio_Dist_Ex > 0)

/* Create wealth and expenditure variables */
gen value = value_agmachinery + value_area + value_nonfarm + value_otherfin + value_poultry + value_tequipment + value_durable
gen log_value = log(1 + value)
gen log_capexp = log(1 + capital_exp)

/****************************************************/
/* SMOOTHNESS CHECKS: HOUSEHOLD CHARACTERISTICS */
/****************************************************/

/* Define number of variables for matrix creation */
global nvars = 10

/* --------- Full sample: Treated districts --------- */
matrix Full_Treat = J(1, $nvars, .)
matrix Full_Treat_sd = J(1, $nvars, .)

tabstat B3_q1 female age education minority_religion minority_social kisan log_B3_q13 log_value log_capexp [w=Weight] if treatment, save s(mean sd)
matrix temp = r(StatTotal)
matrix Full_Treat = temp[1, 1...]
matrix Full_Treat_sd = temp[2, 1...]

/* --------- Full sample: Untreated districts --------- */
matrix Full_Untreat = J(1, $nvars, .)
matrix Full_Untreat_sd = J(1, $nvars, .)

tabstat B3_q1 female age education minority_religion minority_social kisan log_B3_q13 log_value log_capexp [w=Weight] if treatment == 0, save s(mean sd)
matrix temp = r(StatTotal)
matrix Full_Untreat = temp[1, 1...]
matrix Full_Untreat_sd = temp[2, 1...]

/* --------- RDD coefficients --------- */
matrix RDD = J(1, $nvars, .)
matrix RDD_sd = J(1, $nvars, .)

global vars B3_q1 female age education minority_religion minority_social kisan log_B3_q13 log_value log_capexp
local i = 1

foreach x of global vars {
rdrobust `x' B_Ratio_Dist_Ex, p(1) fuzzy(treatment) weights(Weight) vce(cluster NSS_59_Codes) h($h) 
global h_`x' = e(h_l)
matrix RDD[1, `i'] = e(tau_cl)
matrix RDD_sd[1, `i'] = e(se_tau_cl)
local i = `i' + 1
}

/* --------- Restricted sample: Treated districts --------- */
matrix Rest_Treat = J(1, $nvars, .)
matrix Rest_Treat_sd = J(1, $nvars, .)

/* --------- Restricted sample: Untreated districts --------- */
matrix Rest_Untreat = J(1, $nvars, .)
matrix Rest_Untreat_sd = J(1, $nvars, .)

local i = 1
foreach x of global vars {
tabstat `x' [aw=Weight] if treatment==1 & inrange(B_Ratio_Dist_Ex,-$h,$h), ///
stat(mean sd) save
matrix temp = r(StatTotal)
matrix Rest_Treat[1, `i']= temp[1,1]
matrix Rest_Treat_sd[1, `i'] = temp[2,1]

tabstat `x' [aw=Weight] if treatment==0 & inrange(B_Ratio_Dist_Ex,-$h,$h), ///
stat(mean sd) save
matrix temp = r(StatTotal)
matrix Rest_Untreat[1, `i']= temp[1,1]
matrix Rest_Untreat_sd[1, `i'] = temp[2,1]

local i = `i' + 1
}


/* --------- Prepare matrix column names --------- */
global list Full_Treat Full_Treat_sd Full_Untreat Full_Untreat_sd RDD RDD_sd Rest_Treat Rest_Treat_sd Rest_Untreat Rest_Untreat_sd

foreach i of global list {
matrix colnames `i' = dem:B3_q1 dem:female dem:age dem:education dem:minority_religion dem:minority_social dem:kisan inc:log_B3_q13 inc:log_value inc:log_capexp
}

/* --------- Add variable labels --------- */
label variable minority_religion "Religious minority=1"
label variable minority_social "Social Disadvantage=1"
label variable kisan "Kisan card=1"
label variable log_B3_q13 "Consumption (log)"
label variable age "Age of Head"
label variable education "Diploma Head"
label variable female "Female Head=1"
label variable log_value "Value Assets owned (log)"
label variable log_capexp "Capital expenditure (log)"

*------------------------------------------------------------*
* Anchor one stored estimation and attach matrices to it
*------------------------------------------------------------*
eststo clear
quietly regress B3_q1 treatment if !missing(B3_q1, treatment)

estadd matrix Full_Treat, replace
estadd matrix Full_Treat_sd, replace
estadd matrix Full_Untreat, replace
estadd matrix Full_Untreat_sd, replace
estadd matrix RDD, replace
estadd matrix RDD_sd, replace
estadd matrix Rest_Treat, replace
estadd matrix Rest_Treat_sd, replace
estadd matrix Rest_Untreat, replace
estadd matrix Rest_Untreat_sd, replace

eststo smoothhh

/* --------- Export household smoothness table --------- */
esttab smoothhh using "output/tables/table_02_smooth_hh.tex", replace ///
cells("Full_Treat(fmt(2)) Full_Untreat(fmt(2)) Rest_Treat(fmt(2)) Rest_Untreat(fmt(2)) RDD(fmt(2))" ///
  "Full_Treat_sd(par fmt(2)) Full_Untreat_sd(par fmt(2)) Rest_Treat_sd(par fmt(2)) Rest_Untreat_sd(par fmt(2)) RDD_sd(par fmt(2))") ///
booktabs nogap nomtitle label nonum noobs alignment(center) ///
title(Pre smoothness Household) ///
note(Standard deviation/errors in parenthesis.) ///
addn(\sym{*} \(p<0.10\), \sym{**} \(p<0.05\), \sym{***} \(p<0.01\))


/****************************************************/
/* SMOOTHNESS CHECKS: CREDIT MARKET CHARACTERISTICS */
/****************************************************/

use AllIndiaI, clear
eststo clear

/* --------- Prepare credit market data --------- */
destring B15_2_q3, replace
gen b14_q3 = B15_2_q3

/* Merge CPI data for inflation adjustment */
merge m:1 b14_q3 using CPI_index, keepusing(CPI_index)
drop if _merge == 2
drop if B_Ratio_Dist_Ex == .

/* Create inflation-adjusted loan amount */
gen loan_amount = B15_2_q5/CPI_index*100

/* Convert string variables to numeric */
destring NSS_59_Codes, replace
destring State, replace

/* Create log transformations */
local vars "loan_amount B15_2_q10"
foreach i of local vars {
gen log_`i' = log(`i')
summarize log_`i'
generate stdlog_`i' = (log_`i' - r(mean))/r(sd)
}

/* Create state dummies */
forvalues i = 1/36 {
gen state`i' = (State == `i')
}

/* Create loan type variables */
gen short_term = 1 if inlist(B15_2_q8, "1", "2")
replace short_term = 0 if inlist(B15_2_q8, "3", "4")

gen long_term = 1 if inlist(B15_2_q8, "4")
replace long_term = 0 if inlist(B15_2_q8, "1", "2", "3")

gen above = (B_Ratio_Dist_Ex > 0)

/* Create credit agency variables */
gen banks = (inlist(B15_2_q6, "02", "03"))
replace banks = . if B15_2_q6 == ""

gen banksvsml = 1 if (B15_2_q6 == "02", "03")
replace banksvsml = 0 if inlist(B15_2_q6, "10", "11")

/* Define fixed effects */
global fixeffects state3 state6 state8 state9 state10 state11 state12 state14 state17 state18 state19 state20 state21 state23 state24 state27 state28 state29 state32 state33 

/* Rename treatment variable for consistency */
rename treatment Underbanked

/****************************************************/
/* SUMMARY STATISTICS FOR CREDIT MARKET VARIABLES */
/****************************************************/

/* --------- Full sample statistics --------- */
matrix Full_Treat = J(1, 7, .)
matrix Full_Treat_sd = J(1, 7, .)
matrix Full_Untreat = J(1, 7, .)
matrix Full_Untreat_sd = J(1, 7, .)

/* Moneylender loans */
local i = 1
global vars log_i log_loan_amount long_term 
foreach x of global vars {
/* Treated districts - moneylender loans */
tabstat `x' [w=Weight] if Underbanked & inlist(B15_2_q6, "10", "11"), save stats(mean sd)
matrix temp = r(StatTotal)
matrix Full_Treat[1, `i'] = temp[1, 1]
matrix Full_Treat_sd[1, `i'] = temp[2, 1]

/* Untreated districts - moneylender loans */
tabstat `x' [w=Weight] if Underbanked == 0 & inlist(B15_2_q6, "10", "11"), save stats(mean sd)
matrix temp = r(StatTotal)
matrix Full_Untreat[1, `i'] = temp[1, 1]
matrix Full_Untreat_sd[1, `i'] = temp[2, 1]

local i = `i' + 1
}

/* Bank loans */
foreach x of global vars {
/* Treated districts - bank loans */
tabstat `x' [w=Weight] if Underbanked & inlist(B15_2_q6, "02", "03"), save s(mean sd)
matrix temp = r(StatTotal)
matrix Full_Treat[1, `i'] = temp[1, 1]
matrix Full_Treat_sd[1, `i'] = temp[2, 1]

/* Untreated districts - bank loans */
tabstat `x' [w=Weight] if Underbanked == 0 & inlist(B15_2_q6, "02", "03"), save s(mean sd)
matrix temp = r(StatTotal)
matrix Full_Untreat[1, `i'] = temp[1, 1]
matrix Full_Untreat_sd[1, `i'] = temp[2, 1]

local i = `i' + 1
}

/* Bank credit indicator */
tabstat banks [w=Weight] if Underbanked, save s(mean sd)
matrix temp = r(StatTotal)
matrix Full_Treat[1, 7] = temp[1, 1]
matrix Full_Treat_sd[1, 7] = temp[2, 1]

tabstat banks [w=Weight] if Underbanked == 0, save s(mean sd)
matrix temp = r(StatTotal)
matrix Full_Untreat[1, 7] = temp[1, 1]
matrix Full_Untreat_sd[1, 7] = temp[2, 1]

/****************************************************/
/* RDD COEFFICIENTS FOR CREDIT MARKET VARIABLES */
/****************************************************/

matrix RDD = J(1, 7, .)
matrix RDD_sd = J(1, 7, .)

/* Interest rate - Moneylender loans */
rdrobust log_i B_Ratio_Dist_Ex if log_i != . & abs(stdlog_i) < 4 & inlist(B15_2_q6, "10", "11"), p(1) fuzzy(Underbanked) weights(Weight) vce(cluster NSS_59_Codes) h($h) 
global h_log_i = e(h_l)
matrix RDD[1, 1] = e(tau_cl)
matrix RDD_sd[1, 1] = e(se_tau_cl) 

/* Other moneylender loan characteristics */
global vars log_loan_amount long_term
local i = 2

foreach x of global vars {
rdrobust `x' B_Ratio_Dist_Ex if inlist(B15_2_q6, "10", "11"), p(1) fuzzy(Underbanked) weights(Weight) vce(cluster NSS_59_Codes) h($h)
global h_`x' = e(h_l)
matrix RDD[1, `i'] = e(tau_cl)
matrix RDD_sd[1, `i'] = e(se_tau_cl)
local i = `i' + 1
}

/* Interest rate - Bank loans */
rdrobust log_i B_Ratio_Dist_Ex if log_i != . & abs(stdlog_i) < 4 & inlist(B15_2_q6, "02", "03"), p(1) fuzzy(Underbanked) weights(Weight) vce(cluster NSS_59_Codes) h($h) 
global h_log_i = e(h_l)
matrix RDD[1, 4] = e(tau_cl)
matrix RDD_sd[1, 4] = e(se_tau_cl)

/* Other bank loan characteristics */
local i = 5
foreach x of global vars {
rdrobust `x' B_Ratio_Dist_Ex if inlist(B15_2_q6, "02", "03"), p(1) fuzzy(Underbanked) weights(Weight) vce(cluster NSS_59_Codes) h($h) 
global h_`x' = e(h_l)
matrix RDD[1, `i'] = e(tau_cl)
matrix RDD_sd[1, `i'] = e(se_tau_cl)
local i = `i' + 1
}

/* Bank credit indicator */
rdrobust banks B_Ratio_Dist_Ex, p(1) fuzzy(Underbanked) weights(Weight) vce(cluster NSS_59_Codes) h($h)
global h_banks = e(h_l)
matrix RDD[1, 7] = e(tau_cl)
matrix RDD_sd[1, 7] = e(se_tau_cl)

/****************************************************/
/* RESTRICTED SAMPLE STATISTICS FOR CREDIT VARIABLES */
/****************************************************/

matrix Rest_Treat = J(1, 7, .)
matrix Rest_Treat_sd = J(1, 7, .)
matrix Rest_Untreat = J(1, 7, .)
matrix Rest_Untreat_sd = J(1, 7, .)

/* Moneylender loans within bandwidth */
local i = 1
global vars log_i log_loan_amount long_term
foreach x of global vars {
/* Treated districts */
tabstat `x' [w=Weight] if Underbanked & inlist(B15_2_q6, "10", "11") & (B_Ratio_Dist_Ex <= $h & B_Ratio_Dist_Ex >= -$h), save s(mean sd)
matrix temp = r(StatTotal)
matrix Rest_Treat[1, `i'] = temp[1, 1]
matrix Rest_Treat_sd[1, `i'] = temp[2, 1]

/* Untreated districts */
tabstat `x' [w=Weight] if Underbanked == 0 & inlist(B15_2_q6, "10", "11") & (B_Ratio_Dist_Ex <= $h & B_Ratio_Dist_Ex >= -$h), save s(mean sd)
matrix temp = r(StatTotal)
matrix Rest_Untreat[1, `i'] = temp[1, 1]
matrix Rest_Untreat_sd[1, `i'] = temp[2, 1]

local i = `i' + 1
}

/* Bank loans within bandwidth */
foreach x of global vars {
/* Treated districts */
tabstat `x' [w=Weight] if Underbanked & inlist(B15_2_q6, "02", "03") & (B_Ratio_Dist_Ex <= $h & B_Ratio_Dist_Ex >= -$h), save s(mean sd)
matrix temp = r(StatTotal)
matrix Rest_Treat[1, `i'] = temp[1, 1]
matrix Rest_Treat_sd[1, `i'] = temp[2, 1]

/* Untreated districts */
tabstat `x' [w=Weight] if Underbanked == 0 & inlist(B15_2_q6, "02", "03") & (B_Ratio_Dist_Ex <= $h & B_Ratio_Dist_Ex >= -$h), save s(mean sd)
matrix temp = r(StatTotal)
matrix Rest_Untreat[1, `i'] = temp[1, 1]
matrix Rest_Untreat_sd[1, `i'] = temp[2, 1]

local i = `i' + 1
}

/* Bank credit indicator within bandwidth */
tabstat banks [w=Weight] if Underbanked & (B_Ratio_Dist_Ex <= $h & B_Ratio_Dist_Ex >= -$h), save s(mean sd)
matrix temp = r(StatTotal)
matrix Rest_Treat[1, 7] = temp[1, 1]
matrix Rest_Treat_sd[1, 7] = temp[2, 1]

tabstat banks [w=Weight] if Underbanked == 0 & (B_Ratio_Dist_Ex <= $h & B_Ratio_Dist_Ex >= -$h), save s(mean sd)
matrix temp = r(StatTotal)
matrix Rest_Untreat[1, 7] = temp[1, 1]
matrix Rest_Untreat_sd[1, 7] = temp[2, 1]

/****************************************************/
/* PREPARE AND EXPORT CREDIT MARKET SMOOTHNESS TABLE */
/****************************************************/

/* Set matrix column names */
global list Full_Treat Full_Treat_sd Full_Untreat Full_Untreat_sd RDD RDD_sd Rest_Treat Rest_Treat_sd Rest_Untreat Rest_Untreat_sd
foreach i of global list {
matrix colnames `i' = ml:log_i ml:log_loan_amount ml:long_term bn:log_i bn:log_loan_amount bn:long_term tot:banks
}

/* Add variable labels */
label variable log_i "Interest rate (log)"
label variable log_loan_amount "Loan amount (log)"
label variable long_term "Long term loan=1"
label variable banks "Bank credit=1"

eststo clear
quietly regress log_i Underbanked if !missing(log_i, Underbanked)

/* Add matrices to estimates */
estadd matrix Full_Treat, replace
estadd matrix Full_Treat_sd, replace
estadd matrix Full_Untreat, replace
estadd matrix Full_Untreat_sd, replace
estadd matrix RDD, replace
estadd matrix RDD_sd, replace
estadd matrix Rest_Treat, replace
estadd matrix Rest_Treat_sd, replace
estadd matrix Rest_Untreat, replace
estadd matrix Rest_Untreat_sd, replace

/* Export credit market smoothness table */
esttab using "output/tables/table_02_smoothness_credit.tex", replace cells("Full_Treat(fmt(2)) Full_Untreat Rest_Treat Rest_Untreat RDD" "Full_Treat_sd(par) Full_Untreat_sd(par) Rest_Treat_sd(par) Rest_Untreat_sd(par) RDD_sd(par)") booktabs title(Pre smoothness Credits) nogap label nonum noobs alignment(center) note(Standard deviation/errors in parenthesis. Bandwidth in restricted sample forced to be as in the main regression.) addn(\sym{*} \(p<0.10\), \sym{**} \(p<0.05\), \sym{***} \(p<0.01\)) 

}


if `table_C1' {
clear
clear matrix
clear mata

set maxvar 20000

use "MOF_prep_other_researchers.dta", clear
forvalues i=1997(1)2019{
gen log_bnorrb_`i'=log(1+MOF6_func_open_bnorrb_total_`i')
gen log_rrb_`i'=log(1+MOF6_func_open_rrb_total_`i')
gen log_bnorrb_`i'_lic=log(1+MOF6_func_lice_bnorrb_total_`i')
gen log_rrb_`i'_lic=log(1+MOF6_func_lice_rrb_total_`i')
winsor log_bnorrb_`i', generate(log_bnorrb_`i'_w) p(0.01)
winsor log_bnorrb_`i'_lic, generate(log_bnorrb_`i'_lic_w) p(0.01)

}

/** Banks no rural banks**/
eststo clear
forvalues i=2002(1)2019{
eststo:rdrobust log_bnorrb_`i' B_Ratio_Dist_Ex , p(1) fuzzy(B_List_0609_Legal) bwselect(mserd) c(0) covs(log_bnorrb_1997)


*estimates store lic_bnorrb_`i'
global h = e(h_l) 
estadd local bw=round($h) 
estadd local hascontrol "No"
estadd local n_l=e(N_h_l)
estadd local n_r=e(N_h_r)
estimates store bnorrb_`i'
}

esttab using "output/tables/table_C1_supply_norrb_2002_2019.tex", replace  ///
 b(2) se(2) label star(* 0.10 ** 0.05 *** 0.01) ///
 booktabs alignment(center)  nogap nocon noobs noomitted title(Branches Banks without rural banks (log)) mti( "2002" "2003" "2004" "2005" "2006" "2007" "2008" "2009" "2010" "2011" "2012" "2013" "2014" "2015" "2016" "2017" "2018" "2019") scalars("n_l Observations left" "n_r Observations right" "bw Bandwidth" ) sfmt(2)

}


if `table_03' {
/********************/
/* 2003 AIDIS DATA */
/*******************/

use AllIndiaI, clear

/* Keep only moneylender loans */
keep if inlist(B15_2_q6,"10","11") /*Moneylender*/ 

/* Remove outliers */
keep if abs(stdlog_i)<4  /* remove observations beyond 3 standard deviations (2.5%)*/
summ log_i, detail

local p1  = r(p1)
local p99 = r(p99)
drop if log_i==.
drop if B_Ratio_Dist_Ex==.

/* Destring year of loan variable */
destring B15_2_q3, replace

/*****************************/
/* MAIN REGRESSION - 2003 */
/*****************************/

eststo clear
eststo: rdrobust log_i B_Ratio_Dist_Ex if inlist(B15_2_q3, 2000,2001,2002,2003), p(1) fuzzy(treatment) weights(Weight) vce(cluster NSS_59_Codes) bwselect(mserd) 

/* Store bandwidth and sample statistics */
global h = e(h_l)
local h_l = e(h_l)
local h_r = e(h_r)

/* Compute sample mean for loan inside bandwidth */
summarize B15_2_q10 if B_Ratio_Dist_Ex >= -`h_l' & B_Ratio_Dist_Ex <= `h_r' & inlist(B15_2_q3, 2000,2001,2002,2003) [aw=Weight]
local sample_mean = round(r(mean),0.01) 

/* Add statistics to estimates */
estadd local bw=round(e(h_l)) 
estadd local n_l=round(e(N_h_l)) 
estadd local n_r=round(e(N_h_r)) 
estadd local hascontrol "No"
estadd local sample_mean "`sample_mean'"

/*******************/
/* GRAPH FOR 2003  */
/*******************/

rdplot log_i B_Ratio_Dist_Ex if inlist(B15_2_q3, 2000,2001,2002,2003) & inrange(B_Ratio_Dist_Ex,-$h,$h), p(1) weights(Weight) binselect(esmv) fuzzy(treatment) graph_options(graphregion(color(white))) genvars

/* Create custom plot */
set scheme s2color
tw (lfitci log_i  B_Ratio_Dist_Ex if B_Ratio_Dist_Ex<0 & B_Ratio_Dist_Ex>-$h) ///
   (lfitci log_i  B_Ratio_Dist_Ex if B_Ratio_Dist_Ex>0 & B_Ratio_Dist_Ex<$h), ///
   xline(0, lpattern(dash) lcolor("217 85 130")) ///
   legend(off) ///
   xtitle("District level population-to-branch ratio (normalized)", size(large)) ///
   xlabel(, labsize(large)) /// Increase font size of X-axis tick labels
   ylabel(, labsize(large)) /// Increase font size of Y-axis tick labels
   plotregion(fcolor(white)) ///
   graphregion(fcolor(white) lwidth(0)) || (scatter rdplot_mean_y rdplot_mean_x, msize(small) mcolor("45 152 165"))
   
graph export "output/figures/main_result_2003.pdf", replace
graph export "output/figures/main_result_2003.eps", replace

/********************/
/* 2013 AIDIS DATA */
/*******************/

use AllIndiaII, clear

/* Keep only moneylender loans */
keep if inlist(b14_q6,13,14) /*Moneylender*/ 

/* Remove outliers */
keep if abs(stdlog_i)<4  /* remove observations beyond 4 standard deviations*/
drop if log_i==.
drop if B_Ratio_Dist_Ex==.

/*****************************/
/* MAIN REGRESSION - 2013 */
/*****************************/

eststo: rdrobust log_i B_Ratio_Dist_Ex if inlist(b14_q3, 2010,2011,2012,2013), p(1) fuzzy(treatment) weights(Weight_SS) vce(cluster NSS_70_Codes) bwselect(mserd) 

/* Store bandwidth and sample statistics */
global h = e(h_l)
local h_l = e(h_l)
local h_r = e(h_r)

/* Compute sample mean for loan inside bandwidth */
summarize b14_q10 if B_Ratio_Dist_Ex >= -`h_l' & B_Ratio_Dist_Ex <= `h_r' & inlist(b14_q3, 2010,2011,2012,2013) [aw=Weight_SS]
local sample_mean = round(r(mean),0.01) 

/* Add statistics to estimates */
estadd local bw=round(e(h_l)) 
estadd local n_l=round(e(N_h_l)) 
estadd local n_r=round(e(N_h_r)) 
estadd local hascontrol "No"
estadd local sample_mean "`sample_mean'"

/********************/
/* GRAPH FOR 2013 */
/*******************/

rdplot log_i B_Ratio_Dist_Ex if inlist(b14_q3, 2010, 2011,2012,2013) & inrange(B_Ratio_Dist_Ex,-$h,$h), p(1) weights(Weight_SS) binselect(esmv) fuzzy(treatment) graph_options(title("AIDIS_2013") graphregion(color(white))) genvars

/* Create custom plot */
set scheme s2color
tw (lfitci log_i  B_Ratio_Dist_Ex if B_Ratio_Dist_Ex<0 & B_Ratio_Dist_Ex>-$h) ///
   (lfitci log_i  B_Ratio_Dist_Ex if B_Ratio_Dist_Ex>0 & B_Ratio_Dist_Ex<$h), ///
   xline(0, lpattern(dash) lcolor("217 85 130")) ///
   legend(off) ///
   xtitle("District level population-to-branch ratio (normalized)", size(large)) ///
   title("AIDIS 2013", size(huge)) ///
   ytitle("Interest rate by moneylenders (in logs)", size(large)) ///
   xlabel(, labsize(large)) /// Increase font size of X-axis tick labels
   ylabel(, labsize(large)) /// Increase font size of Y-axis tick labels
   plotregion(fcolor(white)) ///
   graphregion(fcolor(white) lwidth(0)) || (scatter rdplot_mean_y rdplot_mean_x, msize(small) mcolor("45 152 165"))
  
graph export "output/figures/main_result.pdf", replace
graph export "output/figures/main_result.eps", replace

/********************/
/* 2019 AIDIS DATA */
/*******************/

use AllIndiaIII.dta, clear

/* Keep only moneylender loans */
keep if inlist(b12q5,"15","16") /*Moneylender*/ 

/* Remove outliers */
keep if abs(stdlog_i)<4  /* remove observations beyond 4 standard deviations*/
drop if log_i==.
drop if B_Ratio_Dist_Ex==.

/*****************************/
/* MAIN REGRESSION - 2019 */
/*****************************/

eststo: rdrobust log_i B_Ratio_Dist_Ex if inlist(b12q2, 2016,2017,2018,2019), p(1) fuzzy(treatment) weights(Weight_SS) vce(cluster NSS_77_Codes) bwselect(mserd) 

/* Store bandwidth and sample statistics */
global h = e(h_l)
local h_l = e(h_l)
local h_r = e(h_r)

/* Compute sample mean for loan inside bandwidth */
summarize b12q9 if B_Ratio_Dist_Ex >= -`h_l' & B_Ratio_Dist_Ex <= `h_r' & inlist(b12q2, 2016,2017,2018,2019) [aw=Weight_SS]
local sample_mean = round(r(mean),0.01) 

/* Add statistics to estimates */
estadd local bw=round(e(h_l)) 
estadd local n_l=round(e(N_h_l)) 
estadd local n_r=round(e(N_h_r)) 
estadd local hascontrol "No"
estadd local sample_mean "`sample_mean'"

/*****************************/
/* EXPORT MAIN RESULTS TABLE */
/*****************************/

esttab using "output/tables/table_03_mainresults.tex", replace  ///
 b(2) se(2) label star(* 0.10 ** 0.05 *** 0.01) ///
 booktabs alignment(center)  nogap nocon noobs noomitted  ///
 mti("2003" "2013" "2019")  scalars("n_l Observations left" "n_r Observations right" "bw Bandwidth"  "hascontrol Controls" "sample_mean Sample Mean") sfmt(2)

/********************/
/* GRAPH FOR 2019 */
/*******************/

rdplot b12q9 B_Ratio_Dist_Ex if inlist(b12q2, 2016,2017,2018,2019) & inrange(B_Ratio_Dist_Ex,-$h,$h), p(1) weights(Weight_SS) binselect(esmv) fuzzy(treatment) graph_options(title("AIDIS_2019") graphregion(color(white))) genvars

/* Create custom plot */
set scheme s2color
tw (lfitci b12q9  B_Ratio_Dist_Ex if B_Ratio_Dist_Ex<0 & B_Ratio_Dist_Ex>-$h) ///
   (lfitci b12q9  B_Ratio_Dist_Ex if B_Ratio_Dist_Ex>0 & B_Ratio_Dist_Ex<$h), ///
   xline(0, lpattern(dash) lcolor("217 85 130")) ///
   legend(off) ///
   xtitle("District level population-to-branch ratio (normalized)", size(large)) ///
   title("AIDIS 2019", size(huge)) ///
   ytitle("Interest rate by moneylenders (%)", size(large)) ///
   xlabel(, labsize(large)) /// Increase font size of X-axis tick labels
   ylabel(, labsize(large)) /// Increase font size of Y-axis tick labels
   plotregion(fcolor(white)) ///
   graphregion(fcolor(white) lwidth(0)) || (scatter rdplot_mean_y rdplot_mean_x, msize(small) mcolor("45 152 165"))
  
graph export "output/figures/main_result_longterm.pdf", replace
graph export "output/figures/main_result_longterm.eps", replace

}


if `table_04' {

use AllIndiaII, clear

/* Keep only moneylender loans; remove outliers and rdrobust for bandwidth */
keep if inlist(b14_q6,13,14) /*Moneylender*/ 

keep if abs(stdlog_i)<4  /* remove observations beyond 4 standard deviations*/
drop if (log_i==. )|(B_Ratio_Dist_Ex==.)

eststo: rdrobust log_i B_Ratio_Dist_Ex if inlist(b14_q3, 2010,2011,2012,2013), p(1) fuzzy(treatment) weights(Weight_SS) vce(cluster NSS_70_Codes) bwselect(mserd) 

/* Store bandwidth*/
global h = e(h_l)

/****************************************************/
/* HOUSEHOLD ASSETS DATA EXTRACTION 				*/
/* Blocks 5-13 & 16: Various household asset data 	*/
/****************************************************/

/* --------- BLOCK 4: Demographic data --------- */
use "70_round\Visit 1 _Block 4_Demographic and other particulars of household members.dta", clear

/* Keep only household heads */
keep if b4q3 == "1"

/* Create demographic variables */
gen female = (b4q4 == "2")
gen education = (inlist(b4q6, "01", "02", "03", "04", "05", "06", "07"))
gen age = b4q5

save "70_round\b4_waveii.dta", replace

/* --------- BLOCK 5: Rural Land ownership --------- */
use "70_round\Visit 1_Block 5pt1_Details of land owned by the household as on 30.06.dta", clear

/* Calculate total land value per household */
gen land_value = ((b5_1_4/100)*b5_1_4)
bysort HHID: egen land_value_rural = total(land_value)
gen land_area = ((b5_1_4/100)*b5_1_5)
bysort HHID: egen land_area_rural = total(land_area)
duplicates drop HHID, force

save "70_round\b5_waveii_1", replace

/* --------- BLOCK 5: Urban Land ownership --------- */
use "70_round\Visit 1_Block 5pt2_Details of land owned by the household as on 30.06.dta", clear

/* Calculate total land value per household */
gen land_value = ((b5_2_4/100)*b5_2_6)
bysort HHID: egen land_value_urban = total(land_value)
gen land_area = ((b5_2_4/100)*b5_2_5)
bysort HHID: egen land_area_urban = total(land_area)
duplicates drop HHID, force

save "70_round\b5_waveii_2", replace

/* --------- BLOCK 6: Buildings and constructions --------- */
use "70_round\Visit 1_Block 6_Buildings and other constructions owned by the household as on 30.06.dta", clear

/* Calculate total building value per household */
gen building_value_own = (b6_q4/100)*b6_q6
bysort HHID: egen building_value = total(building_value_own)
gen building_area_own = (b6_q4/100)*b6_q5
bysort HHID: egen building_area = total(building_area_own)
duplicates drop HHID, force

save "70_round\b6_waveii", replace

/* --------- BLOCK 7: Livestock and poultry --------- */
use "70_round\Visit 1_Block 7_Livestock and poultry owned by the household on 30.06.dta", clear

/* Calculate total livestock/poultry value per household */
bysort HHID: egen value_poultry = total(b7_q5)
duplicates drop HHID, force

save "70_round\b7_waveii", replace

/* --------- BLOCK 8: Transport equipment --------- */
use "70_round\Visit 1_Block 8_Transport equipment owned by the household on 30.06.dta", clear

/* Calculate total transport equipment value per household */
bysort HHID: egen value_tequipment = total(b8_q5)
duplicates drop HHID, force

save "70_round\b8_waveii", replace

/* --------- BLOCK 9: Agricultural machinery --------- */
use "70_round\Visit 1_Block 9_Agricultural machinery and implements owned by the household on 30.06.dta", clear

/* Calculate total agricultural machinery value per household */
bysort HHID: egen value_agmachinery = total(b9_q4)
duplicates drop HHID, force

save "70_round\b9_waveii", replace

/* --------- BLOCK 10: Non-farm business equipment --------- */
use "70_round\Visit 1_Block 10_Non-farm business equipment owned by the household as on 30.06.dta", clear

/* Calculate total non-farm equipment value per household */
bysort HHID: egen value_nonfarm = total(b10_q3)
duplicates drop HHID, force

save "70_round\b10_waveii", replace

/* --------- BLOCK 11: Shares and debentures --------- */
use "70_round\Visit 1_Block 11_ Shares and debentures owned by the household in co-operative  societies & companies as on 30.06.dta", clear

/* Calculate total shares/debentures value per household */
bysort HHID: egen value_shares = total(b11_q3)
duplicates drop HHID, force

save "70_round\b11_waveii", replace

/* --------- BLOCK 12: Other financial assets --------- */
use "70_round\Visit 1_Block 12_Financial assets other than shares and debentures owned by the household as on 30.06.dta", clear

/* Calculate total other financial assets value per household */
bysort HHID: egen value_otherfin = total(b12_q3)
duplicates drop HHID, force

save "70_round\b12_waveii", replace

/* --------- BLOCK 13: Amounts receivable --------- */
use "70_round\Visit 1_Block 13_Amount receivable by the household against different heads as on 30.06.dta", clear

/* Calculate total receivables value per household */
bysort HHID: egen value_rece = total(b13_q4)
duplicates drop HHID, force

save "70_round\b13_waveii", replace

/* --------- BLOCK 16: Capital expenditure --------- */
use "70_round\Visit 1_Block 16_Value (`) of transactions by the household on specified items _capital expenditure.dta", clear

/* Calculate total capital expenditure per household */
bysort HHID: egen capital_exp = total(b16_q9)
duplicates drop HHID, force

save "70_round\b16_waveii", replace

/****************************************************/
/* LOAN DATA PREPARATION AND MERGING 				*/
/****************************************************/

use AllIndiaII, clear
bysort HHID: egen bank = max(inlist(b14_q6, 2, 3))
bysort HHID: egen ml   = max(inlist(b14_q6, 13, 14))
bysort HHID: egen years = max(inlist(b14_q3, 2010, 2011, 2012, 2013))

/****************************************************/
/* MERGE HOUSEHOLD ASSETS DATA 						*/
/****************************************************/

drop _merge 

/* Merge land value data (Block 5) */
merge m:1 HHID using "70_round\b5_waveii_1.dta", keepusing(land_value_rural land_area_rural)
replace land_value_rural = 0 if _merge == 1
replace land_value_rural = 0 if _merge == 1
drop _merge


/* Merge land value data (Block 5) */
merge m:1 HHID using "70_round\b5_waveii_2.dta", keepusing(land_value_urban land_area_urban)
replace land_value_urban = 0 if _merge == 1
replace land_area_urban = 0 if _merge == 1
drop _merge

/* Merge building value data (Block 6) */
merge m:1 HHID using "70_round\b6_waveii.dta", keepusing(building_value building_area)
replace building_value = 0 if _merge == 1
replace building_area = 0 if _merge == 1
drop _merge

/* Merge livestock/poultry value data (Block 7) */
merge m:1 HHID using "70_round\b7_waveii.dta", keepusing(value_poultry)
replace value_poultry = 0 if _merge == 1
drop _merge

/* Merge transport equipment value data (Block 8) */
merge m:1 HHID using "70_round\b8_waveii.dta", keepusing(value_tequipment)
replace value_tequipment = 0 if _merge == 1
drop _merge

/* Merge agricultural machinery value data (Block 9) */
merge m:1 HHID using "70_round\b9_waveii.dta", keepusing(value_agmachinery)
replace value_agmachinery = 0 if _merge == 1
drop _merge

/* Merge non-farm equipment value data (Block 10) */
merge m:1 HHID using "70_round\b10_waveii.dta", keepusing(value_nonfarm)
replace value_nonfarm = 0 if _merge == 1
drop _merge

/* Merge shares/debentures value data (Block 11) */
merge m:1 HHID using "70_round\b11_waveii.dta", keepusing(value_shares)
replace value_shares = 0 if _merge == 1
drop _merge

/* Merge other financial assets value data (Block 12) */
merge m:1 HHID using "70_round\b12_waveii.dta", keepusing(value_otherfin)
replace value_otherfin = 0 if _merge == 1
drop _merge

/* Merge receivables value data (Block 13) */
merge m:1 HHID using "70_round\b13_waveii.dta", keepusing(value_rece)
replace value_rece = 0 if _merge == 1
drop _merge

/* Merge capital expenditure data (Block 16) */
merge m:1 HHID using "70_round\b16_waveii.dta", keepusing(capital_exp)
replace capital_exp = 0 if _merge == 1
drop _merge

/****************************************************/
/* CREATE WEALTH AND EXPENDITURE VARIABLES 			*/
/****************************************************/

/* Calculate total household asset value */
gen value = value_agmachinery + land_value_rural + land_value_urban + building_value + value_nonfarm + value_otherfin + value_poultry + value_rece + value_shares + value_tequipment


/* Create log-transformed wealth variables */
gen log_value = log(1 + value)
gen log_capexp = log(1 + capital_exp)

duplicates drop HHID, force
preserve
keep HHID value log_value
rename log_value log_total_value
save HH_wealth, replace
restore

/********************************************************/
/* REGRESSION DISCONTINUITY ANALYSIS - HOUSEHOLD WEALTH */
/********************************************************/

/* 1. RDD on household wealth (all households) */
eststo clear
global vars "log_value log_capexp"
foreach x of global vars{
eststo:rdrobust `x' B_Ratio_Dist_Ex, p(1) fuzzy(treatment) weights(Weight_SS) vce(cluster NSS_70_Codes) h($h) 
estadd local bw=round(e(h_l)) 
estadd local n_l=round(e(N_h_l)) 
estadd local n_r=round(e(N_h_r)) 
estadd local hascontrol "No"
* Choose the corresponding LEVEL variable for the mean
    local meanvar ""
    if "`x'" == "log_value"  local meanvar "value"
    if "`x'" == "log_capexp" local meanvar "capital_exp"
summarize `meanvar' if abs(B_Ratio_Dist_Ex) <= $h & inlist(years,1) [aw=Weight_SS]
local sample_mean = round(r(mean),1) 
estadd local sample_mean "`sample_mean'"
}

/* 2. RDD on household wealth (moneylender borrowers only) */
foreach x of global vars{
eststo:rdrobust `x' B_Ratio_Dist_Ex if inlist(ml,1) & inlist(years,1), p(1) fuzzy(treatment) weights(Weight_SS) vce(cluster NSS_70_Codes) h($h)
estadd local bw=round(e(h_l)) 
estadd local n_l=round(e(N_h_l)) 
estadd local n_r=round(e(N_h_r)) 
estadd local hascontrol "No"
* Choose the corresponding LEVEL variable for the mean
    local meanvar ""
    if "`x'" == "log_value"  local meanvar "value"
    if "`x'" == "log_capexp" local meanvar "capital_exp"
	
summarize `meanvar' if abs(B_Ratio_Dist_Ex) <= $h & inlist(years,1) & inlist(ml,1) [aw=Weight_SS]
local sample_mean = round(r(mean),1) 
estadd local sample_mean "`sample_mean'"
}

/* 3. RDD on household wealth (formal bank borrowers only) */
foreach x of global vars{
eststo:rdrobust `x' B_Ratio_Dist_Ex if inlist(bank,1) & inlist(years,1), p(1) fuzzy(treatment) weights(Weight_SS) vce(cluster NSS_70_Codes) h($h)
estadd local bw=round(e(h_l)) 
estadd local n_l=round(e(N_h_l)) 
estadd local n_r=round(e(N_h_r)) 
estadd local hascontrol "No"
* Choose the corresponding LEVEL variable for the mean
    local meanvar ""
    if "`x'" == "log_value"  local meanvar "value"
    if "`x'" == "log_capexp" local meanvar "capital_exp"
	
summarize `meanvar' if abs(B_Ratio_Dist_Ex) <= $h & inlist(bank,1) [aw=Weight_SS]
local sample_mean = round(r(mean),1) 
estadd local sample_mean "`sample_mean'"
}

esttab using "output/tables/table_04_channel_wealth.tex", replace  ///
 b(2) se(2) label star(* 0.10 ** 0.05 *** 0.01) ///
 booktabs alignment(center)  nogap nocon noobs noomitted  ///
 title(Channel 2) mti("Value assets" "Capital expend." "Value assets" "Capital expend." "Value assets" "Capital expend.") mgroups("Total" "Moneylender" "Banks" , pattern(1 0 1 0 1 0 1 0)  prefix(\multicolumn{@span}{c}{) suffix(})span erepeat(\cmidrule(lr){@span}))  scalars("n_l Observations left" "n_r Observations right" "bw Bandwidth" "hascontrol Controls" "sample_mean Sample Mean" ) sfmt(2) 
 
}


if `table_05' {

use AllIndiaII, clear
keep if inlist(b14_q6,13,14) /*Moneylender*/ 
keep if abs(stdlog_i)<4  /* remove observations beyond 3 standard deviations (2.5%)*/
drop if log_i==.|B_Ratio_Dist_Ex==.

eststo clear
eststo: rdrobust log_i B_Ratio_Dist_Ex if inlist(b14_q3, 2010,2011,2012,2013), p(1) fuzzy(treatment) weights(Weight_SS) vce(cluster NSS_70_Codes) bwselect(mserd) 

/* Store bandwidth and sample statistics */
global h = e(h_l)

/****************************************************/
/* TABLE 6: LOAN AMOUNT EFFECTS (LOAN-LEVEL) */
/****************************************************/

use "AllIndiaII.dta", clear
keep if inlist(b14_q3, 2010, 2011, 2012, 2013)

* Merge CPI data for inflation adjustment
drop _merge
merge m:1 b14_q3 using CPI_index, keepusing(CPI_index)
drop if _merge == 2
drop _merge

* CPI-adjusted loan amount (levels)
gen loan_amount = b14_q5 / CPI_index * 100

* Log loan amount (drop nonpositive / missing)
gen log_loan_amount = log(loan_amount) if loan_amount > 0

* Make cluster id numeric if needed
destring NSS_70_Codes, replace force
* If your district variable is NSS_70_Codes instead, use that:
* destring NSS_70_Codes, replace force



eststo clear

/********** (1) Any loan: loan-level amounts **********/
eststo: rdrobust log_loan_amount B_Ratio_Dist_Ex ///
if !missing(log_loan_amount) , ///
p(1) fuzzy(treatment) weights(Weight_SS) vce(cluster NSS_70_Codes) h($h)

local h_l = e(h_l)
local h_r = e(h_r)

summarize loan_amount if inrange(B_Ratio_Dist_Ex, -`h_l', `h_r') & !missing(log_loan_amount) [aw=Weight_SS]
local sample_mean = round(r(mean))

estadd local bw = round(e(h_l))
estadd local n_l = round(e(N_h_l))
estadd local n_r = round(e(N_h_r))
estadd local hascontrol "No"
estadd local sample_mean "`sample_mean'"


/********** (2) Bank loans only **********/
eststo: rdrobust log_loan_amount B_Ratio_Dist_Ex ///
if inlist(b14_q6, 2, 3) & !missing(log_loan_amount), ///
p(1) fuzzy(treatment) weights(Weight_SS) vce(cluster NSS_70_Codes) h($h)

local h_l = e(h_l)
local h_r = e(h_r)

summarize loan_amount if inrange(B_Ratio_Dist_Ex, -`h_l', `h_r') & inlist(b14_q6, 2, 3) & !missing(log_loan_amount) [aw=Weight_SS]
local sample_mean = round(r(mean))

estadd local bw = round(e(h_l))
estadd local n_l = round(e(N_h_l))
estadd local n_r = round(e(N_h_r))
estadd local hascontrol "No"
estadd local sample_mean "`sample_mean'"


/********** (3) Moneylender loans only **********/
eststo: rdrobust log_loan_amount B_Ratio_Dist_Ex ///
if inlist(b14_q6, 13, 14) & !missing(log_loan_amount), ///
p(1) fuzzy(treatment) weights(Weight_SS) vce(cluster NSS_70_Codes) h($h)

local h_l = e(h_l)
local h_r = e(h_r)

summarize loan_amount if inrange(B_Ratio_Dist_Ex, -`h_l', `h_r') & inlist(b14_q6, 13, 14) & !missing(log_loan_amount) [aw=Weight_SS]
local sample_mean = round(r(mean))

estadd local bw = round(e(h_l))
estadd local n_l = round(e(N_h_l))
estadd local n_r = round(e(N_h_r))
estadd local hascontrol "No"
estadd local sample_mean "`sample_mean'"


/********** Export **********/
esttab using "output/tables/table_05_channel_loan_amount_loanlevel.tex", replace ///
b(2) se(2) label star(* 0.10 ** 0.05 *** 0.01) ///
booktabs alignment(center) nogap nocon noobs noomitted ///
title(Channel) mti("Any loan" "Bank loan" "ML loan") ///
scalars("n_l Observations left" "n_r Observations right" "bw Bandwidth" "hascontrol Controls" "sample_mean Sample Mean") ///
sfmt(2)

}


if `table_06'  {

use "AllIndiaII.dta", clear
keep if inlist(b14_q3, 2010, 2011, 2012, 2013)
drop _merge

/* Merge CPI data for inflation adjustment */
merge m:1 b14_q3 using CPI_index, keepusing(CPI_index)
drop if _merge == 2
gen loan_amount = b14_q5 / CPI_index * 100

/****************************************************/
/* CREATE LOAN AMOUNT DATASETS - 2013 */
/****************************************************/

/* --------- All loans dataset --------- */
keep HHID loan_amount
bysort HHID: egen tot_amount = total(loan_amount)
gen avg_amount = loan_amount
collapse (sum) tot_amount (mean) avg_amount, by(HHID)
save "70_round\HH_2013_loans.dta", replace

/* --------- Moneylender loans dataset --------- */
use "AllIndiaII.dta", clear
keep if inlist(b14_q3, 2010, 2011, 2012, 2013) & inlist(b14_q6,13,14)
drop _merge
merge m:1 b14_q3 using CPI_index, keepusing(CPI_index)
drop if _merge == 2
gen loan_amount = b14_q5 / CPI_index * 100

keep HHID loan_amount
bysort HHID: egen tot_amount_ML = total(loan_amount)
gen avg_amount_ML = loan_amount
collapse (sum) tot_amount_ML (mean) avg_amount_ML, by(HHID)
save "70_round\HH_2013_ML_loans.dta", replace

/* --------- Bank loans dataset --------- */
use "AllIndiaII.dta", clear
keep if inlist(b14_q3, 2010, 2011, 2012, 2013) & inlist(b14_q6,2,3)
drop _merge
merge m:1 b14_q3 using CPI_index, keepusing(CPI_index)
drop if _merge == 2
gen loan_amount = b14_q5 / CPI_index * 100

keep HHID loan_amount
bysort HHID: egen tot_amount_bank = total(loan_amount)
gen avg_amount_bank = loan_amount
collapse (sum) tot_amount_bank (mean) avg_amount_bank, by(HHID)
save "70_round\HH_2013_bank_loans.dta", replace

/* --------- Create moneylender-only HH dataset --------- */
use "AllIndiaII.dta", clear
keep if inlist(b14_q3, 2010, 2011, 2012, 2013)
keep HHID b14_q6 
gen ML_loan_share = (inlist(b14_q6,13,14))
collapse (mean) ML_loan_share, by(HHID)
sum ML_loan_share
keep if ML_loan_share == 1
save "70_round\HH_2013_ML_loans_only.dta", replace

/****************************************************/
/* CREATE MASTER HOUSEHOLD DATASET - 2013 */
/****************************************************/

use "70_round/b4_waveii.dta", clear

/* Merge all loan datasets */
merge 1:1 HHID using "70_round\HH_2013_loans"
gen loan = (_merge == 3)
drop _merge

merge 1:1 HHID using "70_round\HH_2013_ML_loans"
gen ML_loan = (_merge == 3)
drop _merge

merge 1:1 HHID using "70_round\HH_2013_bank_loans"
gen bank_loan = (_merge == 3)
drop _merge

merge 1:1 HHID using "70_round\HH_2013_ML_loans_only"
gen ML_loan_only = (_merge == 3)
drop _merge
tab ML_loan_only

/* Create combined loan indicators */
gen ML_bank_loan = (bank_loan == 1 & ML_loan == 1)
tab ML_bank_loan

rename State_District NSS_70_Codes

merge m:1 NSS_70_Codes using "MOF_Census_NSS_70.dta"
destring NSS_70_Codes, replace


/************************/
/* LOAN TAKEUP ANALYSIS */
/************************/

eststo clear

/* --------- Loan takeup probability analysis --------- */

/* Any loan takeup */
eststo: rdrobust loan B_Ratio_Dist_Ex, p(1) fuzzy(treatment) weights(Weight_SS) vce(cluster NSS_70_Codes) h($h)
local h_l = e(h_l)
local h_r = e(h_r)
summarize loan if B_Ratio_Dist_Ex >= -`h_l' & B_Ratio_Dist_Ex <= `h_r' [aw=Weight_SS]
local sample_mean = round(r(mean), 0.01)
estadd local bw = round(e(h_l)) 
estadd local n_l = round(e(N_h_l)) 
estadd local n_r = round(e(N_h_r)) 
estadd local hascontrol "No"
estadd local sample_mean "`sample_mean'"

/* Bank loan takeup (conditional on any loan) */
eststo: rdrobust bank_loan B_Ratio_Dist_Ex if loan == 1, p(1) fuzzy(treatment) weights(Weight_SS) vce(cluster NSS_70_Codes) h($h)
local h_l = e(h_l)
local h_r = e(h_r)
summarize bank_loan if B_Ratio_Dist_Ex >= -`h_l' & B_Ratio_Dist_Ex <= `h_r' & loan == 1 [aw=Weight_SS]
local sample_mean = round(r(mean), 0.01)
estadd local bw = round(e(h_l)) 
estadd local n_l = round(e(N_h_l)) 
estadd local n_r = round(e(N_h_r)) 
estadd local hascontrol "No"
estadd local sample_mean "`sample_mean'"

/* Moneylender loan takeup (conditional on any loan) */
eststo: rdrobust ML_loan B_Ratio_Dist_Ex if loan == 1, p(1) fuzzy(treatment) weights(Weight_SS) vce(cluster NSS_70_Codes) h($h) 
local h_l = e(h_l)
local h_r = e(h_r)
summarize ML_loan if B_Ratio_Dist_Ex >= -`h_l' & B_Ratio_Dist_Ex <= `h_r' & loan == 1 [aw=Weight_SS]
local sample_mean = round(r(mean), 0.01)
estadd local bw = round(e(h_l)) 
estadd local n_l = round(e(N_h_l)) 
estadd local n_r = round(e(N_h_r)) 
estadd local hascontrol "No"
estadd local sample_mean "`sample_mean'"

/* Moneylender-only loan takeup */
eststo: rdrobust ML_loan_only B_Ratio_Dist_Ex if loan == 1, p(1) fuzzy(treatment) weights(Weight_SS) vce(cluster NSS_70_Codes) h($h)
local h_l = e(h_l)
local h_r = e(h_r)
summarize ML_loan_only if B_Ratio_Dist_Ex >= -`h_l' & B_Ratio_Dist_Ex <= `h_r' & loan == 1 [aw=Weight_SS]
local sample_mean = round(r(mean), 0.01)
estadd local bw = round(e(h_l)) 
estadd local n_l = round(e(N_h_l)) 
estadd local n_r = round(e(N_h_r)) 
estadd local hascontrol "No"
estadd local sample_mean "`sample_mean'"

/* Both bank and moneylender loan takeup */
eststo: rdrobust ML_bank_loan B_Ratio_Dist_Ex if loan == 1, p(1) fuzzy(treatment) weights(Weight_SS) vce(cluster NSS_70_Codes) h($h) 
local h_l = e(h_l)
local h_r = e(h_r)
summarize ML_bank_loan if B_Ratio_Dist_Ex >= -`h_l' & B_Ratio_Dist_Ex <= `h_r' & loan == 1 [aw=Weight_SS]
local sample_mean = round(r(mean), 0.01)
estadd local bw = round(e(h_l)) 
estadd local n_l = round(e(N_h_l)) 
estadd local n_r = round(e(N_h_r)) 
estadd local hascontrol "No"
estadd local sample_mean "`sample_mean'"

/* Export loan takeup results */
esttab using "output/tables/table_06_channel_loan_takeup.tex", replace ///
b(2) se(2) label star(* 0.10 ** 0.05 *** 0.01) ///
booktabs alignment(center) nogap nocon noobs noomitted ///
title(Channel) mti("loan=1" "Bank loan=1" "ML loan=1" "ML loan only" "Bank+ML loan=1") ///
scalars("n_l Observations left" "n_r Observations right" "bw Bandwidth" "hascontrol Controls" "sample_mean Sample Mean") sfmt(2)

}


if `table_07' {

/* DISTRICT-LEVEL LOAN ANALYSIS */

use "AllIndiaII.dta", clear
keep if inlist(b14_q3, 2010, 2011, 2012, 2013)

/* Create loan count variables */
gen n = 1
gen n_ML = (inlist(b14_q6,13,14))
gen n_bank = (inlist(b14_q6,2,3))

/* Collapse to district level */
collapse (rawsum) n n_ML n_bank [pweight = Weight_SS], by(NSS_70_Codes)

/* Prepare for saving */
destring NSS_70_Codes, replace
save district_loans, replace

/****************************************************/
/* MAIN REGRESSION WITH ADDITIONAL CONTROLS			*/
/****************************************************/

use AllIndiaII, clear
keep if abs(stdlog_i)<4  /* remove observations beyond 4 standard deviations*/
drop if log_i==.
drop if B_Ratio_Dist_Ex==.

tabulate b14_q8, gen(loantype) /*This is loan period, short medium and long term*/
*tabulate b14_q4, gen(loanperiod) /*Not actually loan period, is something else*/
gen purpose = 1
replace purpose = 6 if inlist(b14_q11, 1, 2)
replace purpose = 5 if inlist(b14_q11, 3, 4)
replace purpose = 4 if inlist(b14_q11, 8)
replace purpose = 3 if inlist(b14_q11, 10)
replace purpose = 2 if inlist(b14_q11, 11)
tab purpose
tabulate purpose, gen(loanpurpose) /*Loan purpose*/

tabulate b14_q3, gen(loanyear)
*loan amount b14_q5
*year of loan b14_q3
forvalues i=1(1)36{
	gen state`i' =(State==`i' )
}

drop _merge
merge m:1 b14_q3 using CPI_index, keepusing(CPI_index)
drop if _merge==2
drop if B_Ratio_Dist_Ex==.
gen loan_amount= b14_q5/CPI_index*100


global fixeffects state3 state6 state8 state9 state10 state11 state12 state14 state17 state18 state19 state20 state21 state23 state24 state27 state28 state29 state32 state33 

drop _merge
merge m:1 HHID using HH_wealth
keep if _merge==3
drop _merge

merge m:1 NSS_70_Codes using district_loans
keep if _merge==3
drop _merge

merge m:1 HHID using "70_round/b4_waveii", keep(match) nogen keepusing(b4q6)

merge m:1 HHID using "70_round/Visit 1_Block 3_Household Characteristics", keep(match) nogen keepusing(b3q1 b3q5 b3q6 b3q7 b3q13)

/* Create demographic and socioeconomic variables */
gen minority_religion = (b3q6 == "2" | b3q6 == "3" | b3q6 == "7" | b3q6 == "9")
gen minority_social = (b3q7 == "1"| b3q7 == "2")
gen kisan = (b3q13 == "1")

gen log_loan_amount = log(loan_amount)

eststo clear
* no controls (Main)
eststo: rdrobust log_i B_Ratio_Dist_Ex if inlist(b14_q3, 2010,2011,2012,2013) & inlist(b14_q6,13,14), p(1) fuzzy(treatment) weights(Weight_SS) vce(cluster NSS_70_Codes) bwselect(mserd) // h($h) 

* Extract the left and right bandwidths
local h_l = e(h_l)
local h_r = e(h_r)
* Compute sample mean for loan inside the bandwidth
summarize b14_q10 if B_Ratio_Dist_Ex >= -`h_l' & B_Ratio_Dist_Ex <= `h_r' & inlist(b14_q3, 2010,2011,2012,2013) & inlist(b14_q6,13,14) [aw=Weight_SS]
local sample_mean = round(r(mean),0.01) 
estadd local bw=round(e(h_l)) 
estadd local n_l=round(e(N_h_l)) 
estadd local n_r=round(e(N_h_r)) 
estadd local hascontrol "No"
estadd local sample_mean "`sample_mean'"

* loan characteristics
eststo: rdrobust log_i B_Ratio_Dist_Ex if inlist(b14_q3, 2010,2011,2012,2013) & inlist(b14_q6,13,14), p(1) covs(log_loan_amount loanpurpose1 loanpurpose2 loanpurpose3 loanpurpose4 loanpurpose5 loantype2 loantype3 loantype4) fuzzy(treatment) weights(Weight_SS) vce(cluster NSS_70_Codes) h($h) 
* Extract the left and right bandwidths
local h_l = e(h_l)
local h_r = e(h_r)
* Compute sample mean for loan inside the bandwidth
summarize b14_q10 if B_Ratio_Dist_Ex >= -`h_l' & B_Ratio_Dist_Ex <= `h_r' & inlist(b14_q3, 2010,2011,2012,2013) & inlist(b14_q6,13,14) [aw=Weight_SS]
local sample_mean = round(r(mean),0.01) 
estadd local bw=round(e(h_l)) 
estadd local n_l=round(e(N_h_l)) 
estadd local n_r=round(e(N_h_r)) 
estadd local hascontrol "Yes"
estadd local sample_mean "`sample_mean'"

* HH wealth
eststo: rdrobust log_i B_Ratio_Dist_Ex if inlist(b14_q3, 2010,2011,2012,2013) & inlist(b14_q6,13,14), p(1) covs(log_total_value) fuzzy(treatment) weights(Weight_SS) vce(cluster NSS_70_Codes) h($h) 
* Extract the left and right bandwidths
local h_l = e(h_l)
local h_r = e(h_r)
* Compute sample mean for loan inside the bandwidth
summarize b14_q10 if B_Ratio_Dist_Ex >= -`h_l' & B_Ratio_Dist_Ex <= `h_r' & inlist(b14_q3, 2010,2011,2012,2013) & inlist(b14_q6,13,14) [aw=Weight_SS]
local sample_mean = round(r(mean),0.01) 
estadd local bw=round(e(h_l)) 
estadd local n_l=round(e(N_h_l)) 
estadd local n_r=round(e(N_h_r)) 
estadd local hascontrol "Yes"
estadd local sample_mean "`sample_mean'"

* District characteristics (loan takeup + new bank branches)
eststo: rdrobust log_i B_Ratio_Dist_Ex if inlist(b14_q3, 2010,2011,2012,2013) & inlist(b14_q6,13,14), p(1) covs(n n_bank n_ML) fuzzy(treatment) weights(Weight_SS) vce(cluster NSS_70_Codes) h($h) 
* Extract the left and right bandwidths
local h_l = e(h_l)
local h_r = e(h_r)
* Compute sample mean for loan inside the bandwidth
summarize b14_q10 if B_Ratio_Dist_Ex >= -`h_l' & B_Ratio_Dist_Ex <= `h_r' & inlist(b14_q3, 2010,2011,2012,2013) & inlist(b14_q6,13,14) [aw=Weight_SS]
local sample_mean = round(r(mean),0.01) 
estadd local bw=round(e(h_l)) 
estadd local n_l=round(e(N_h_l)) 
estadd local n_r=round(e(N_h_r)) 
estadd local hascontrol "Yes"
estadd local sample_mean "`sample_mean'"

* all controls together
eststo: rdrobust log_i B_Ratio_Dist_Ex if inlist(b14_q3, 2010,2011,2012,2013) & inlist(b14_q6,13,14), p(1) covs(log_loan_amount loanpurpose1 loanpurpose2 loanpurpose3 loanpurpose4 loanpurpose5 loantype2 loantype3 loantype4 log_loan_amount log_total_value n n_bank n_ML) fuzzy(treatment) weights(Weight_SS) vce(cluster NSS_70_Codes) h($h) 

* Extract the left and right bandwidths
local h_l = e(h_l)
local h_r = e(h_r)
* Compute sample mean for loan inside the bandwidth
summarize b14_q10 if B_Ratio_Dist_Ex >= -`h_l' & B_Ratio_Dist_Ex <= `h_r' & inlist(b14_q3, 2010,2011,2012,2013) & inlist(b14_q6,13,14) [aw=Weight_SS]
local sample_mean = round(r(mean),0.01) 
estadd local bw=round(e(h_l)) 
estadd local n_l=round(e(N_h_l)) 
estadd local n_r=round(e(N_h_r)) 
estadd local hascontrol "Yes"
estadd local sample_mean "`sample_mean'"

esttab using "output/tables/table_07_mainresult_with_controls.tex", replace  ///
 b(2) se(2) label star(* 0.10 ** 0.05 *** 0.01) ///
 booktabs alignment(center)  nogap nocon noobs noomitted  ///
 mti("No controls" "Loan char." "Wealth" "Loan takeup" "All") scalars("n_l Observations left" "n_r Observations right" "bw Bandwidth"  "hascontrol Controls" "sample_mean Sample Mean") sfmt(2)

}


if `table_C2' {

/****************************************************/
/* HOUSEHOLD ASSETS DATA PREPARATION - 2013 WAVE 	*/
/****************************************************/

/* Set base directory for NSS Round 70 data */
local base_dir "`c(pwd)'\70_round"

/* --------- BLOCK 4: Demographic data --------- */
use "`base_dir'\Visit 1 _Block 4_Demographic and other particulars of household members.dta", clear

/* Keep only household heads */
keep if b4q3 == "1"

/* Create demographic variables */
gen female = (b4q4 == "2")
gen education = (inlist(b4q6, "01", "02", "03", "04", "05", "06", "07"))
gen age = b4q5

save "70_round\b4_waveii.dta", replace

/****************************************************/
/* LOAN DATA PREPARATION AND MERGING */
/****************************************************/

use AllIndiaII, clear

/* Create dummy variables for loan characteristics */
tabulate b14_q8, gen(loantype)  /* This is loan period, short medium and long term */
tabulate b14_q4, gen(loanperiod) /* Not actually loan period, is something else */

/* Create treatment indicator variables */
gen above = (B_Ratio_Dist_Ex > 0)
gen inter = above * B_Ratio_Dist_Ex

/****************************************************/
/* MERGE HOUSEHOLD IDENTIFICATION AND CHARACTERISTICS */
/****************************************************/

/* Merge household identification data */
drop _merge
merge m:1 HHID using "`base_dir'\Visit 1_Block 1&2_Identification of sample household and particulars of field operations.dta", force
rename _merge _mergev1

/* Merge household characteristics data */
merge m:1 HHID using "`base_dir'\Visit 1_Block 3_Household Characteristics.dta", force
drop _merge

/* Merge demographic data (Block 4) */
merge m:1 HHID using "`base_dir'\b4_waveii.dta", keepusing(age education female) force
drop _merge

/****************************************************/
/* CREATE SOCIOECONOMIC VARIABLES */
/****************************************************/

/* Create loan receipt indicator */
gen get_loan = (_mergev1 == 3)

/* Convert string variables to numeric */
destring b3q1, replace
destring b3q5, replace

/* Create demographic and socioeconomic variables */
gen minority_religion = (b3q6 == "2" | b3q6 == "3" | b3q6 == "7" | b3q6 == "9")
gen minority_social = (b3q7 == "1" | b3q7 == "2")
gen kisan = (b3q13 == "1")

/****************************************************/
/* SMOOTHNESS CHECKS: POST-TREATMENT CHARACTERISTICS */
/****************************************************/

/* Define number of variables for matrix creation */
global n_vars = 21

/* --------- Full sample: Treated districts --------- */
matrix Full_Treat = J(1, $n_vars, .)
matrix Full_Treat_sd = J(1, $n_vars, .)

/* Total sample (all loan recipients) */
tabstat b3q1 female age education minority_religion minority_social kisan [w=Weight_SS] if treatment & get_loan, save s(mean sd)
matrix Full_Treat[1, 1] = r(StatTotal)[1, 1...]
matrix Full_Treat_sd[1, 1] = r(StatTotal)[2, 1...]

/* Moneylender loan recipients */
tabstat b3q1 female age education minority_religion minority_social kisan [w=Weight_SS] if treatment & inlist(b14_q6,13,14), save s(mean sd)
matrix Full_Treat[1, 8] = r(StatTotal)[1, 1...]
matrix Full_Treat_sd[1, 8] = r(StatTotal)[2, 1...]

/* Bank loan recipients */
tabstat b3q1 female age education minority_religion minority_social kisan [w=Weight_SS] if treatment & inlist(b14_q6, 2, 3), save s(mean sd)
matrix Full_Treat[1, 15] = r(StatTotal)[1, 1...]
matrix Full_Treat_sd[1, 15] = r(StatTotal)[2, 1...]

/* --------- Full sample: Untreated districts --------- */
matrix Full_Untreat = J(1, $n_vars, .)
matrix Full_Untreat_sd = J(1, $n_vars, .)

/* Total sample (all loan recipients) */
tabstat b3q1 female age education minority_religion minority_social kisan [w=Weight_SS] if treatment == 0 & get_loan, save s(mean sd)
matrix Full_Untreat[1, 1] = r(StatTotal)[1, 1...]
matrix Full_Untreat_sd[1, 1] = r(StatTotal)[2, 1...]

/* Moneylender loan recipients */
tabstat b3q1 female age education minority_religion minority_social kisan [w=Weight_SS] if treatment == 0 & inlist(b14_q6,13,14), save s(mean sd)
matrix Full_Untreat[1, 8] = r(StatTotal)[1, 1...]
matrix Full_Untreat_sd[1, 8] = r(StatTotal)[2, 1...]

/* Bank loan recipients */
tabstat b3q1 female age education minority_religion minority_social kisan [w=Weight_SS] if treatment == 0 & inlist(b14_q6, 2, 3), save s(mean sd)
matrix Full_Untreat[1, 15] = r(StatTotal)[1, 1...]
matrix Full_Untreat_sd[1, 15] = r(StatTotal)[2, 1...]

/* --------- RDD coefficients --------- */
matrix RDD = J(1, $n_vars, .)
matrix RDD_sd = J(1, $n_vars, .)

global vars b3q1 female age education minority_religion minority_social kisan

/* Total sample RDD coefficients */
local i = 1
foreach x of global vars {
rdrobust `x' B_Ratio_Dist_Ex if get_loan, p(1) fuzzy(treatment) weights(Weight_SS) vce(cluster NSS_70_Codes) bwselect(mserd) 
global h_`x' = e(h_l)
global h = e(h_l)
matrix RDD[1, `i'] = e(b)[1, 1]
matrix RDD_sd[1, `i'] = e(se_tau_cl)
local i = `i' + 1
}

/* Moneylender loan recipients RDD coefficients */
local i = 8
foreach x of global vars {
rdrobust `x' B_Ratio_Dist_Ex if inlist(b14_q6,13,14), p(1) fuzzy(treatment) weights(Weight_SS) vce(cluster NSS_70_Codes) bwselect(mserd) 
global h_`x' = e(h_l)
global h = e(h_l)
matrix RDD[1, `i'] = e(b)[1, 1]
matrix RDD_sd[1, `i'] = e(se_tau_cl)
local i = `i' + 1
}

/* Bank loan recipients RDD coefficients */
local i = 15
foreach x of global vars {
rdrobust `x' B_Ratio_Dist_Ex if inlist(b14_q6, 2, 3), p(1) fuzzy(treatment) weights(Weight_SS) vce(cluster NSS_70_Codes) bwselect(mserd) 
global h_`x' = e(h_l)
global h = e(h_l)
matrix RDD[1, `i'] = e(b)[1, 1]
matrix RDD_sd[1, `i'] = e(se_tau_cl)
local i = `i' + 1
}

/* --------- Restricted sample: Treated districts --------- */
matrix Rest_Treat = J(1, $n_vars, .)
matrix Rest_Treat_sd = J(1, $n_vars, .)

/* --------- Restricted sample: Untreated districts --------- */
matrix Rest_Untreat = J(1, $n_vars, .)
matrix Rest_Untreat_sd = J(1, $n_vars, .)

/* Total sample restricted statistics */
local i = 1
foreach x of global vars {
global h = ${h_`x'}

/* Treated districts within bandwidth */
tabstat `x' [w=Weight_SS] if treatment & (B_Ratio_Dist_Ex <= $h & B_Ratio_Dist_Ex >= -$h) & get_loan, save s(mean sd)
matrix Rest_Treat[1, `i'] = r(StatTotal)[1, 1]
matrix Rest_Treat_sd[1, `i'] = r(StatTotal)[2, 1]

/* Untreated districts within bandwidth */
tabstat `x' [w=Weight_SS] if treatment == 0 & (B_Ratio_Dist_Ex <= $h & B_Ratio_Dist_Ex >= -$h) & get_loan, save s(mean sd)
matrix Rest_Untreat[1, `i'] = r(StatTotal)[1, 1]
matrix Rest_Untreat_sd[1, `i'] = r(StatTotal)[2, 1]

local i = `i' + 1
}

/* Moneylender loan recipients restricted statistics */
local i = 8
foreach x of global vars {
global h = ${h_`x'}

/* Treated districts within bandwidth */
tabstat `x' [w=Weight_SS] if treatment & (B_Ratio_Dist_Ex <= $h & B_Ratio_Dist_Ex >= -$h) & inlist(b14_q6,13,14), save s(mean sd)
matrix Rest_Treat[1, `i'] = r(StatTotal)[1, 1]
matrix Rest_Treat_sd[1, `i'] = r(StatTotal)[2, 1]

/* Untreated districts within bandwidth */
tabstat `x' [w=Weight_SS] if treatment == 0 & (B_Ratio_Dist_Ex <= $h & B_Ratio_Dist_Ex >= -$h) & inlist(b14_q6,13,14), save s(mean sd)
matrix Rest_Untreat[1, `i'] = r(StatTotal)[1, 1]
matrix Rest_Untreat_sd[1, `i'] = r(StatTotal)[2, 1]

local i = `i' + 1
}

/* Bank loan recipients restricted statistics */
local i = 15
foreach x of global vars {
global h = ${h_`x'}

/* Treated districts within bandwidth */
tabstat `x' [w=Weight_SS] if treatment & (B_Ratio_Dist_Ex <= $h & B_Ratio_Dist_Ex >= -$h) & inlist(b14_q6, 2, 3), save s(mean sd)
matrix Rest_Treat[1, `i'] = r(StatTotal)[1, 1]
matrix Rest_Treat_sd[1, `i'] = r(StatTotal)[2, 1]

/* Untreated districts within bandwidth */
tabstat `x' [w=Weight_SS] if treatment == 0 & (B_Ratio_Dist_Ex <= $h & B_Ratio_Dist_Ex >= -$h) & inlist(b14_q6, 2, 3), save s(mean sd)
matrix Rest_Untreat[1, `i'] = r(StatTotal)[1, 1]
matrix Rest_Untreat_sd[1, `i'] = r(StatTotal)[2, 1]

local i = `i' + 1
}

/****************************************************/
/* PREPARE MATRICES FOR EXPORT */
/****************************************************/

/* Set matrix column names */
global list Full_Treat Full_Treat_sd Full_Untreat Full_Untreat_sd RDD RDD_sd Rest_Treat Rest_Treat_sd Rest_Untreat Rest_Untreat_sd
foreach i of global list {
matrix colnames `i' = tot:b3q1 tot:female tot:age tot:education tot:minority_religion tot:minority_social tot:kisan ml:b3q1 ml:female ml:age ml:education ml:minority_religion ml:minority_social ml:kisan bk:b3q1 bk:female bk:age bk:education bk:minority_religion bk:minority_social bk:kisan
}

/* Add variable labels */
label variable minority_religion "Religious minority=1"
label variable minority_social "Social Disadvantage=1"
label variable kisan "Kisan card=1"
label variable b3q1 "Household size=1"
label variable age "Age of Head"
label variable education "Diploma Head=1"
label variable female "Female Head=1"

eststo clear
quietly regress log_i treatment if !missing(log_i, treatment)

/* Add matrices to estimates */
estadd matrix Full_Treat, replace
estadd matrix Full_Treat_sd, replace
estadd matrix Full_Untreat, replace
estadd matrix Full_Untreat_sd, replace
estadd matrix RDD, replace
estadd matrix RDD_sd, replace
estadd matrix Rest_Treat, replace
estadd matrix Rest_Treat_sd, replace
estadd matrix Rest_Untreat, replace
estadd matrix Rest_Untreat_sd, replace

/****************************************************/
/* EXPORT POST-TREATMENT SMOOTHNESS TABLE */
/****************************************************/

esttab using "output/tables/table_C2_smooth_wave2.tex", replace cells("Full_Treat(fmt(2)) Full_Untreat Rest_Treat Rest_Untreat RDD" "Full_Treat_sd(par) Full_Untreat_sd(par) Rest_Treat_sd(par) Rest_Untreat_sd(par) RDD_sd(par)") tex title(Post smoothness Household) nogap nomtitle label nonum noobs alignment(center) note(Standard deviation/errors in parenthesis.) addn(\sym{*} \(p<0.10\), \sym{**} \(p<0.05\), \sym{***} \(p<0.01\))
}


if `table_C3' {

use AllIndiaII.dta, clear

/* Prepare data */
keep if abs(stdlog_i)<4  /* remove observations beyond 4 standard deviations*/
drop if log_i==.
drop if B_Ratio_Dist_Ex==.

/* Create state dummies */
forvalues i=1(1)36{
	gen state`i' =(State==`i' )
}

/* Define state fixed effects */
global fixeffects state3 state6 state8 state9 state10 state11 state12 state14 state17 state18 state19 state20 state21 state23 state24 state27 state28 state29 state32 state33

/* Merge CPI data */
drop _merge
merge m:1 b14_q3 using CPI_index, keepusing(CPI_index)
drop if _merge==2

/* Generate loan_amount variable */
gen loan_amount= b14_q5/CPI_index*100


/******************************************************/
/* TABLE 11: ROBUSTNESS: PLACEBO CUTOFFS  */
/******************************************************/

global mean=14953

/* Create placebo cutoff variables */
gen ratio_demean=(ratio_banks-$mean)
gen ratio_demean_n1000=(B_Ratio_Dist_Ex-1000)
gen ratio_demean_n2000=(B_Ratio_Dist_Ex-2000)
gen ratio_demean_n3000=(B_Ratio_Dist_Ex-3000)
gen ratio_demean_p1000=(B_Ratio_Dist_Ex+1000)
gen ratio_demean_p2000=(B_Ratio_Dist_Ex+2000)
gen ratio_demean_p3000=(B_Ratio_Dist_Ex+3000)

/* Get bandwidth for placebo tests */
rdrobust log_i B_Ratio_Dist_Ex if  inlist(b14_q3, 2010, 2011,2012,2013) & inlist(b14_q6,13,14), p(1) fuzzy(treatment) weights(Weight_SS) vce(cluster NSS_70_Codes) bwselect(mserd)
global h = e(h_l)

eststo clear

/* Run placebo tests at different cutoffs */
local placebo_vars ratio_demean_n3000 ratio_demean_n2000 ratio_demean_n1000 ratio_demean ratio_demean_p1000 ratio_demean_p2000 ratio_demean_p3000

foreach var in `placebo_vars' {
eststo: rdrobust log_i `var' if inlist(b14_q3, 2010, 2011,2012,2013) & inlist(b14_q6,13,14), p(1) fuzzy(treatment) weights(Weight_SS) vce(cluster NSS_70_Codes) c(0) h($h)
local h_l = e(h_l)
local h_r = e(h_r)
summarize b14_q10 if B_Ratio_Dist_Ex >= -`h_l' & B_Ratio_Dist_Ex <= `h_r' & inlist(b14_q3, 2010,2011,2012,2013) & inlist(b14_q6, 13, 14) [aw=Weight_SS]
local sample_mean = round(r(mean),0.01) 
estadd local bw=round(e(h_l)) 
estadd local n_l=round(e(N_h_l)) 
estadd local n_r=round(e(N_h_r)) 
estadd local hascontrol "No"
estadd local sample_mean "`sample_mean'"
}

/* Export placebo cutoff results */
esttab using "output/tables/table_C3_mainresult_robustness_cutoffs.tex", replace  ///
 b(2) se(2) label star(* 0.10 ** 0.05 *** 0.01) ///
 booktabs alignment(center)  nogap nocon noobs noomitted  ///
 mti("-3000" "-2000" "-1000" "0 (Main)" "+1000" "+2000" "+3000") scalars("n_l Observations left" "n_r Observations right" "bw Bandwidth"  "hascontrol Controls" "sample_mean Sample Mean") sfmt(2)

}


if `table_C4' {
/******************************************************/
/* TABLE 12: ROBUSTNESS: DIFFERENT POLYNOMIAL ORDERS  */
/******************************************************/

* Make sure the instrument exists
cap drop above
gen above = (B_Ratio_Dist_Ex >= 0) if !missing(B_Ratio_Dist_Ex)

* One bandwidth (p=1 baseline), force everywhere
rdrobust log_i B_Ratio_Dist_Ex if inlist(b14_q3,2010,2011,2012,2013) & inlist(b14_q6, 13, 14), p(1) fuzzy(treatment) weights(Weight_SS) vce(cluster NSS_70_Codes) bwselect(mserd)
global h = e(h_l)

* Compute Obs left/right ONCE (same for all cols), using the same RD window
quietly count if inlist(b14_q3,2010,2011,2012,2013) & inrange(B_Ratio_Dist_Ex,-$h,$h) & B_Ratio_Dist_Ex < 0 & !missing(log_i,treatment,Weight_SS,B_Ratio_Dist_Ex) & inlist(b14_q6, 13, 14)
global N_L = r(N)
quietly count if inlist(b14_q3,2010,2011,2012,2013) & inrange(B_Ratio_Dist_Ex,-$h,$h) & B_Ratio_Dist_Ex >= 0 & !missing(log_i,treatment,Weight_SS,B_Ratio_Dist_Ex) & inlist(b14_q6, 13, 14)
global N_R = r(N)

* Helper: post tau/se into e(b) with name RD_Estimate
cap program drop _post_rd
program define _post_rd, eclass
    syntax , TAU(real) SE(real)
    tempname b V
    matrix `b' = (`tau')
    matrix colnames `b' = RD_Estimate
    matrix `V' = (`se')^2
    matrix colnames `V' = RD_Estimate
    matrix rownames `V' = RD_Estimate
    ereturn post `b' `V'
end

eststo clear

/********** A) rdrobust (NO FE): p = 0..3, forced bandwidth **********/
forvalues p = 0/3 {

    capture noisily rdrobust log_i B_Ratio_Dist_Ex if inlist(b14_q3,2010,2011,2012,2013) & inlist(b14_q6, 13, 14), p(`p') fuzzy(treatment) weights(Weight_SS) vce(cluster NSS_70_Codes) h($h)

    if _rc == 0 {
        local tau = e(tau_cl)
        local se  = e(se_tau_cl)
    }
    else {
        local tau = .
        local se  = .
    }

    eststo rd_p`p': _post_rd, tau(`tau') se(`se')

    summarize b14_q10 if B_Ratio_Dist_Ex >= -`h_l' & B_Ratio_Dist_Ex <= `h_r' & inlist(b14_q3, 2010,2011,2012,2013) & inlist(b14_q6, 13, 14) [aw=Weight_SS]
	local sample_mean = round(r(mean),0.01) 

    estadd local bw = round($h)
    estadd local n_l = $N_L
    estadd local n_r = $N_R
    estadd local hascontrol "No"
    estadd local sample_mean "`sample_mean'"
}

/********** B) FE version (manual 2SLS): p = 0..2 **********/
forvalues p = 0/2 {

    if `p' == 0 {
        local poly_vars ""
        local inst_vars "above"
    }
    else if `p' == 1 {
        local poly_vars "c.B_Ratio_Dist_Ex"
        local inst_vars "above c.B_Ratio_Dist_Ex"
    }
    else if `p' == 2 {
        local poly_vars "c.B_Ratio_Dist_Ex##c.B_Ratio_Dist_Ex"
        local inst_vars "above c.B_Ratio_Dist_Ex##c.B_Ratio_Dist_Ex"
    }

    quietly ivregress 2sls log_i `poly_vars' (treatment = `inst_vars') $fixeffects [w=Weight_SS] if inlist(b14_q3,2010,2011,2012,2013) & inrange(B_Ratio_Dist_Ex,-$h,$h) & inlist(b14_q6, 13, 14), cluster(NSS_70_Codes)

    * Post the FE treatment effect as RD_Estimate so it shows in the SAME ROW
    local tau = _b[treatment]
    local se  = _se[treatment]
    eststo fe_p`p': _post_rd, tau(`tau') se(`se')

    summarize b14_q10 if B_Ratio_Dist_Ex >= -`h_l' & B_Ratio_Dist_Ex <= `h_r' & inlist(b14_q3, 2010,2011,2012,2013) & inlist(b14_q6, 13, 14) [aw=Weight_SS]
	local sample_mean = round(r(mean),0.01) 

    estadd local bw = round($h)
    estadd local n_l = $N_L
    estadd local n_r = $N_R
    estadd local hascontrol "Yes"
    estadd local sample_mean "`sample_mean'"
}

* Export (now RD_Estimate is filled in ALL columns; n_l/n_r filled in ALL columns)
esttab rd_p0 rd_p1 rd_p2 rd_p3 fe_p0 fe_p1 fe_p2 using "output/tables/table_C4_robustness_polynomials.tex", replace keep(RD_Estimate) b(2) se(2) label star(* 0.10 ** 0.05 *** 0.01) booktabs alignment(center) nogap nocon noobs noomitted mti("p(0)" "p(1)" "p(2)" "p(3)" "p(0)FE" "p(1)FE" "p(2)FE") scalars("n_l Observations left" "n_r Observations right" "bw Bandwidth" "hascontrol State FE" "sample_mean Sample Mean") sfmt(2)


}


if `table_C5' {

/***************************************************************/
/* TABLE 13: ROBUSTNESS: DIFFERENT BANDWIDTH SELECTION METHODS */
/***************************************************************/

eststo clear

local bw_methods mserd msetwo msesum cerrd certwo cersum

foreach method in `bw_methods' {
eststo: rdrobust log_i B_Ratio_Dist_Ex if inlist(b14_q3, 2010,2011,2012,2013) & inlist(b14_q6, 13, 14), p(1) fuzzy(treatment) weights(Weight_SS) vce(cluster NSS_70_Codes) bwselect(`method') 
local h_l = e(h_l)
local h_r = e(h_r)
summarize b14_q10 if B_Ratio_Dist_Ex >= -`h_l' & B_Ratio_Dist_Ex <= `h_r' & inlist(b14_q3, 2010,2011,2012,2013) & inlist(b14_q6, 13, 14) [aw=Weight_SS]
local sample_mean = round(r(mean),0.01) 
estadd local bw_l=round(e(h_l)) 
estadd local bw_r=round(e(h_r)) 
estadd local n_l=round(e(N_h_l)) 
estadd local n_r=round(e(N_h_r)) 
estadd local hascontrol "No"
estadd local sample_mean "`sample_mean'"
}

/* Export bandwidth selection results */
esttab using "output/tables/Table_C5_robustness_bandwidth.tex", replace  ///
 b(2) se(2) label star(* 0.10 ** 0.05 *** 0.01) ///
 booktabs alignment(center)  nogap nocon noobs noomitted  ///
 mti("mserd" "msetwo" "msesum" "cerrd" "certwo" "cersum") scalars("n_l Observations left" "n_r Observations right" "bw_l Bandwidth Left" "bw_r Bandwidth Right" "hascontrol Controls" "sample_mean Sample Mean") sfmt(2)
 

 
}


if `table_C6' {


global h = 7861

use "AllIndiaI.dta", clear
keep if inlist(B15_2_q3, "2000","2001","2002","2003")

* Create loan type indicators
gen ML_loan = (inlist(B15_2_q6,"10", "11"))
gen bank_loan = (inlist(B15_2_q6,"02", "03"))

* Create term indicators
gen short_term = (inlist(B15_2_q8,"1","2"))
gen medium_term = (inlist(B15_2_q8,"3"))
gen long_term = (inlist(B15_2_q8,"4"))

gen short_term_bank = short_term & bank_loan
gen medium_term_bank = medium_term & bank_loan
gen long_term_bank = long_term & bank_loan

gen short_term_ML = short_term & ML_loan
gen medium_term_ML = medium_term & ML_loan
gen long_term_ML = long_term & ML_loan

******* Referee 2 comment 2a - THE FINAL TABLE ************

eststo clear
eststo: rdrobust short_term B_Ratio_Dist_Ex, p(1) fuzzy(treatment) weights(Weight) vce(cluster NSS_59_Codes) h($h)
* Extract the left and right bandwidths
local h_l = e(h_l)
local h_r = e(h_r)
* Compute sample mean for loan inside the bandwidth
summarize short_term if B_Ratio_Dist_Ex >= -`h_l' & B_Ratio_Dist_Ex <= `h_r' [aw=Weight]
local sample_mean = round(r(mean),0.01) 
estadd local bw=round(e(h_l)) 
estadd local n_l=round(e(N_h_l)) 
estadd local n_r=round(e(N_h_r)) 
estadd local hascontrol "No"
estadd local sample_mean "`sample_mean'"

eststo: rdrobust medium_term B_Ratio_Dist_Ex, p(1) fuzzy(treatment) weights(Weight) vce(cluster NSS_59_Codes) h($h) 
* Extract the left and right bandwidths
local h_l = e(h_l)
local h_r = e(h_r)
* Compute sample mean for loan inside the bandwidth
summarize medium_term if B_Ratio_Dist_Ex >= -`h_l' & B_Ratio_Dist_Ex <= `h_r' [aw=Weight]
local sample_mean = round(r(mean),0.01) 
estadd local bw=round(e(h_l)) 
estadd local n_l=round(e(N_h_l)) 
estadd local n_r=round(e(N_h_r)) 
estadd local hascontrol "No"
estadd local sample_mean "`sample_mean'"

eststo: rdrobust long_term B_Ratio_Dist_Ex, p(1) fuzzy(treatment) weights(Weight) vce(cluster NSS_59_Codes) h($h)
* Extract the left and right bandwidths
local h_l = e(h_l)
local h_r = e(h_r)
* Compute sample mean for loan inside the bandwidth
summarize long_term if B_Ratio_Dist_Ex >= -`h_l' & B_Ratio_Dist_Ex <= `h_r' [aw=Weight]
local sample_mean = round(r(mean),0.01) 
estadd local bw=round(e(h_l)) 
estadd local n_l=round(e(N_h_l)) 
estadd local n_r=round(e(N_h_r)) 
estadd local hascontrol "No"
estadd local sample_mean "`sample_mean'"

eststo: rdrobust short_term_bank B_Ratio_Dist_Ex if bank_loan==1, p(1) fuzzy(treatment) weights(Weight) vce(cluster NSS_59_Codes) h($h) 
* Extract the left and right bandwidths
local h_l = e(h_l)
local h_r = e(h_r)
* Compute sample mean for loan inside the bandwidth
summarize short_term_bank if B_Ratio_Dist_Ex >= -`h_l' & B_Ratio_Dist_Ex <= `h_r' & bank_loan==1 [aw=Weight]
local sample_mean = round(r(mean),0.01) 
estadd local bw=round(e(h_l)) 
estadd local n_l=round(e(N_h_l)) 
estadd local n_r=round(e(N_h_r)) 
estadd local hascontrol "No"
estadd local sample_mean "`sample_mean'"

eststo: rdrobust medium_term_bank B_Ratio_Dist_Ex if bank_loan==1, p(1) fuzzy(treatment) weights(Weight) vce(cluster NSS_59_Codes) h($h) 
* Extract the left and right bandwidths
local h_l = e(h_l)
local h_r = e(h_r)
* Compute sample mean for loan inside the bandwidth
summarize medium_term_bank if B_Ratio_Dist_Ex >= -`h_l' & B_Ratio_Dist_Ex <= `h_r' & bank_loan==1 [aw=Weight]
local sample_mean = round(r(mean),0.01) 
estadd local bw=round(e(h_l)) 
estadd local n_l=round(e(N_h_l)) 
estadd local n_r=round(e(N_h_r)) 
estadd local hascontrol "No"
estadd local sample_mean "`sample_mean'"

eststo: rdrobust long_term_bank B_Ratio_Dist_Ex if bank_loan==1, p(1) fuzzy(treatment) weights(Weight) vce(cluster NSS_59_Codes) h($h)
* Extract the left and right bandwidths
local h_l = e(h_l)
local h_r = e(h_r)
* Compute sample mean for loan inside the bandwidth
summarize long_term_bank if B_Ratio_Dist_Ex >= -`h_l' & B_Ratio_Dist_Ex <= `h_r' & bank_loan==1 [aw=Weight]
local sample_mean = round(r(mean),0.01) 
estadd local bw=round(e(h_l)) 
estadd local n_l=round(e(N_h_l)) 
estadd local n_r=round(e(N_h_r)) 
estadd local hascontrol "No"
estadd local sample_mean "`sample_mean'"

eststo: rdrobust short_term_ML B_Ratio_Dist_Ex if ML_loan==1, p(1) fuzzy(treatment) weights(Weight) vce(cluster NSS_59_Codes) h($h)
* Extract the left and right bandwidths
local h_l = e(h_l)
local h_r = e(h_r)
* Compute sample mean for loan inside the bandwidth
summarize short_term_ML if B_Ratio_Dist_Ex >= -`h_l' & B_Ratio_Dist_Ex <= `h_r' & ML_loan==1 [aw=Weight]
local sample_mean = round(r(mean),0.01) 
estadd local bw=round(e(h_l)) 
estadd local n_l=round(e(N_h_l)) 
estadd local n_r=round(e(N_h_r)) 
estadd local hascontrol "No"
estadd local sample_mean "`sample_mean'"

eststo: rdrobust medium_term_ML B_Ratio_Dist_Ex if ML_loan==1, p(1) fuzzy(treatment) weights(Weight) vce(cluster NSS_59_Codes) h($h)
* Extract the left and right bandwidths
local h_l = e(h_l)
local h_r = e(h_r)
* Compute sample mean for loan inside the bandwidth
summarize medium_term_ML if B_Ratio_Dist_Ex >= -`h_l' & B_Ratio_Dist_Ex <= `h_r' & ML_loan==1 [aw=Weight]
local sample_mean = round(r(mean),0.01) 
estadd local bw=round(e(h_l)) 
estadd local n_l=round(e(N_h_l)) 
estadd local n_r=round(e(N_h_r)) 
estadd local hascontrol "No"
estadd local sample_mean "`sample_mean'"

eststo: rdrobust long_term_ML B_Ratio_Dist_Ex if ML_loan==1, p(1) fuzzy(treatment) weights(Weight) vce(cluster NSS_59_Codes) h($h)
* Extract the left and right bandwidths
local h_l = e(h_l)
local h_r = e(h_r)
* Compute sample mean for loan inside the bandwidth
summarize long_term_ML if B_Ratio_Dist_Ex >= -`h_l' & B_Ratio_Dist_Ex <= `h_r' & ML_loan==1 [aw=Weight]
local sample_mean = round(r(mean),0.01) 
estadd local bw=round(e(h_l)) 
estadd local n_l=round(e(N_h_l)) 
estadd local n_r=round(e(N_h_r)) 
estadd local hascontrol "No"
estadd local sample_mean "`sample_mean'"

* Export the table
esttab using "output/tables/table_C6_short_long_term_2003_table.tex", replace ///
    b(2) se(2) label star(* 0.10 ** 0.05 *** 0.01) ///
	booktabs alignment(center)  nogap nocon noobs noomitted  ///
	title(Channel) mti("Short Any" "Medium Any" "Long Any" "Short Bank" "Medium Bank" "Long Bank" "Short ML" "Medium ML" "Long ML") ///
	scalars("n_l Observations left" "n_r Observations right" "bw Bandwidth" "hascontrol Controls" "sample_mean Sample Mean") sfmt(2)
	
}

	
if `table_C7' {

global h = 7861

use "AllIndiaII.dta", clear
keep if inlist(b14_q3, 2010,2011,2012,2013)

* Create loan type indicators
gen ML_loan = (inlist(b14_q6,13, 14))
gen bank_loan = (inlist(b14_q6,2, 3))

* Create term indicators
gen short_term = (inlist(b14_q8,1,2))
gen medium_term = (inlist(b14_q8,3))
gen long_term = (inlist(b14_q8,4))

gen short_term_bank = short_term & bank_loan
gen medium_term_bank = medium_term & bank_loan
gen long_term_bank = long_term & bank_loan

gen short_term_ML = short_term & ML_loan
gen medium_term_ML = medium_term & ML_loan
gen long_term_ML = long_term & ML_loan

******* Referee 2 comment 2a - THE FINAL TABLE ************

eststo clear
eststo: rdrobust short_term B_Ratio_Dist_Ex, p(1) fuzzy(treatment) weights(Weight_SS) vce(cluster NSS_70_Codes) h($h)
* Extract the left and right bandwidths
local h_l = e(h_l)
local h_r = e(h_r)
* Compute sample mean for loan inside the bandwidth
summarize short_term if B_Ratio_Dist_Ex >= -`h_l' & B_Ratio_Dist_Ex <= `h_r' [aw=Weight_SS]
local sample_mean = round(r(mean),0.01) 
estadd local bw=round(e(h_l)) 
estadd local n_l=round(e(N_h_l)) 
estadd local n_r=round(e(N_h_r)) 
estadd local hascontrol "No"
estadd local sample_mean "`sample_mean'"

eststo: rdrobust medium_term B_Ratio_Dist_Ex, p(1) fuzzy(treatment) weights(Weight_SS) vce(cluster NSS_70_Codes) h($h) 
* Extract the left and right bandwidths
local h_l = e(h_l)
local h_r = e(h_r)
* Compute sample mean for loan inside the bandwidth
summarize medium_term if B_Ratio_Dist_Ex >= -`h_l' & B_Ratio_Dist_Ex <= `h_r' [aw=Weight_SS]
local sample_mean = round(r(mean),0.01) 
estadd local bw=round(e(h_l)) 
estadd local n_l=round(e(N_h_l)) 
estadd local n_r=round(e(N_h_r)) 
estadd local hascontrol "No"
estadd local sample_mean "`sample_mean'"

eststo: rdrobust long_term B_Ratio_Dist_Ex, p(1) fuzzy(treatment) weights(Weight_SS) vce(cluster NSS_70_Codes) h($h)
* Extract the left and right bandwidths
local h_l = e(h_l)
local h_r = e(h_r)
* Compute sample mean for loan inside the bandwidth
summarize long_term if B_Ratio_Dist_Ex >= -`h_l' & B_Ratio_Dist_Ex <= `h_r' [aw=Weight_SS]
local sample_mean = round(r(mean),0.01) 
estadd local bw=round(e(h_l)) 
estadd local n_l=round(e(N_h_l)) 
estadd local n_r=round(e(N_h_r)) 
estadd local hascontrol "No"
estadd local sample_mean "`sample_mean'"

eststo: rdrobust short_term_bank B_Ratio_Dist_Ex if bank_loan==1, p(1) fuzzy(treatment) weights(Weight_SS) vce(cluster NSS_70_Codes) h($h) 
* Extract the left and right bandwidths
local h_l = e(h_l)
local h_r = e(h_r)
* Compute sample mean for loan inside the bandwidth
summarize short_term_bank if B_Ratio_Dist_Ex >= -`h_l' & B_Ratio_Dist_Ex <= `h_r' & bank_loan==1 [aw=Weight_SS]
local sample_mean = round(r(mean),0.01) 
estadd local bw=round(e(h_l)) 
estadd local n_l=round(e(N_h_l)) 
estadd local n_r=round(e(N_h_r)) 
estadd local hascontrol "No"
estadd local sample_mean "`sample_mean'"

eststo: rdrobust medium_term_bank B_Ratio_Dist_Ex if bank_loan==1, p(1) fuzzy(treatment) weights(Weight_SS) vce(cluster NSS_70_Codes) h($h) 
* Extract the left and right bandwidths
local h_l = e(h_l)
local h_r = e(h_r)
* Compute sample mean for loan inside the bandwidth
summarize medium_term_bank if B_Ratio_Dist_Ex >= -`h_l' & B_Ratio_Dist_Ex <= `h_r' & bank_loan==1 [aw=Weight_SS]
local sample_mean = round(r(mean),0.01) 
estadd local bw=round(e(h_l)) 
estadd local n_l=round(e(N_h_l)) 
estadd local n_r=round(e(N_h_r)) 
estadd local hascontrol "No"
estadd local sample_mean "`sample_mean'"

eststo: rdrobust long_term_bank B_Ratio_Dist_Ex if bank_loan==1, p(1) fuzzy(treatment) weights(Weight_SS) vce(cluster NSS_70_Codes) h($h)
* Extract the left and right bandwidths
local h_l = e(h_l)
local h_r = e(h_r)
* Compute sample mean for loan inside the bandwidth
summarize long_term_bank if B_Ratio_Dist_Ex >= -`h_l' & B_Ratio_Dist_Ex <= `h_r' & bank_loan==1 [aw=Weight_SS]
local sample_mean = round(r(mean),0.01) 
estadd local bw=round(e(h_l)) 
estadd local n_l=round(e(N_h_l)) 
estadd local n_r=round(e(N_h_r)) 
estadd local hascontrol "No"
estadd local sample_mean "`sample_mean'"

eststo: rdrobust short_term_ML B_Ratio_Dist_Ex if ML_loan==1, p(1) fuzzy(treatment) weights(Weight_SS) vce(cluster NSS_70_Codes) h($h)
* Extract the left and right bandwidths
local h_l = e(h_l)
local h_r = e(h_r)
* Compute sample mean for loan inside the bandwidth
summarize short_term_ML if B_Ratio_Dist_Ex >= -`h_l' & B_Ratio_Dist_Ex <= `h_r' & ML_loan==1 [aw=Weight_SS]
local sample_mean = round(r(mean),0.01) 
estadd local bw=round(e(h_l)) 
estadd local n_l=round(e(N_h_l)) 
estadd local n_r=round(e(N_h_r)) 
estadd local hascontrol "No"
estadd local sample_mean "`sample_mean'"

eststo: rdrobust medium_term_ML B_Ratio_Dist_Ex if ML_loan==1, p(1) fuzzy(treatment) weights(Weight_SS) vce(cluster NSS_70_Codes) h($h)
* Extract the left and right bandwidths
local h_l = e(h_l)
local h_r = e(h_r)
* Compute sample mean for loan inside the bandwidth
summarize medium_term_ML if B_Ratio_Dist_Ex >= -`h_l' & B_Ratio_Dist_Ex <= `h_r' & ML_loan==1 [aw=Weight_SS]
local sample_mean = round(r(mean),0.01) 
estadd local bw=round(e(h_l)) 
estadd local n_l=round(e(N_h_l)) 
estadd local n_r=round(e(N_h_r)) 
estadd local hascontrol "No"
estadd local sample_mean "`sample_mean'"

eststo: rdrobust long_term_ML B_Ratio_Dist_Ex if ML_loan==1, p(1) fuzzy(treatment) weights(Weight_SS) vce(cluster NSS_70_Codes) h($h)
* Extract the left and right bandwidths
local h_l = e(h_l)
local h_r = e(h_r)
* Compute sample mean for loan inside the bandwidth
summarize long_term_ML if B_Ratio_Dist_Ex >= -`h_l' & B_Ratio_Dist_Ex <= `h_r' & ML_loan==1 [aw=Weight_SS]
local sample_mean = round(r(mean),0.01) 
estadd local bw=round(e(h_l)) 
estadd local n_l=round(e(N_h_l)) 
estadd local n_r=round(e(N_h_r)) 
estadd local hascontrol "No"
estadd local sample_mean "`sample_mean'"

* Export the table
esttab using "output/tables/table_C7_short_long_term_2013_table.tex", replace ///
    b(2) se(2) label star(* 0.10 ** 0.05 *** 0.01) ///
	booktabs alignment(center)  nogap nocon noobs noomitted  ///
	title(Channel) mti("Short Any" "Medium Any" "Long Any" "Short Bank" "Medium Bank" "Long Bank" "Short ML" "Medium ML" "Long ML") ///
	scalars("n_l Observations left" "n_r Observations right" "bw Bandwidth" "hascontrol Controls" "sample_mean Sample Mean") sfmt(2)
	
}